I am having problems with vue.js when it comes to pushing data from the database to the webpage. I am using laravel 5.3 which converts data to Jason. the code posts to the server the number of records to be fetched then the server response with the data in which i want to display on the webpage. here is Vue js Code
new Vue({
el: "#projects",
data: {
count: 0,
fetched_projects: []
}
methods:{
checkproject: function(){
var fetch = this.count += 4;
axios.post('/loadmore', {fetch: fetch })
.then(function(response) {
this.fetched_projects.push(response.data);
})
.catch(function(error){
console.log(error);
});
}
HTML
<div class="row">
<div class="col-md-3">
<ul v-for="more_projects in fetched_projects">
<li>#{{ more_projects }}</li>
</ul>
</div>
</div>
Laravel controller
public function setloadMore(Request $request){
$new_projects = $request->fetch;
$results = Model1::with('relation')->take($new_projects)->get();
return $results;
}
The problem is on this.fetched_projects.push(response.data); its giving me "cannot read property 'push' of undifined"
You'd want this to be your component, so use an arrow function:
methods:{
checkproject: function(){
var fetch = this.count += 4;
axios.post('/loadmore', {fetch: fetch })
.then(response => {
this.fetched_projects.push(response.data);
})
.catch(function(error){
console.log(error);
});
}
you are having "this" problem, try defining something like var that = this where you have defined fetch, and use that in place of this inside the post it should work.
Related
I'm having a problem with a Vue template where no elements on the page will not render unless an array declared on data is already populated.
The problem is that the data is only populated after an API call made by submitting a form.
The browser console reads Error in render: "TypeError: Cannot read property 'response' of undefined"
If I comment out the {{classes.data.response}} the form displays but will not otherwise.
Here is what the code looks like.
<template>
<div class="container">
<form #submit="getClass">
<input type="text" placeholder="Search..." v-model="class_id">
<button type="submit">Search</button>
</form>
<br>
<div v-if="classes"> <!-- conditionally render if array has results -->
{{classes.data.response}} <!-- form shows when this is commented out -->
</div>
</div>
</template>
The data block
data() {
return {
classes: []
};
},
...
And the methods block
methods: {
...
// Request
axios(config)
.then(response => (this.classes = response))
.catch(function (error) {
console.log('There was an error :' , error);
});
}
}
I'm relatively new to Vue so if anyone can tell me what is going wrong here I'd much appreciate it. Thanks in advance!
this.classes.data.response is not defined
You can try to be more specific when assigning the response to classes. Instead of this.classes = response, do this this.classes = response.data.response. response.data.response is the Array you are looking for, not response.
methods: {
...
// Request
axios(config)
.then(response => (this.classes = response.data.response))
.catch(function (error) {
console.log('There was an error :' , error);
});
}
}
Then in the template just write {{ classes }} instead of {{ classes.data.response }}, also v-if="classes.length > 0" instead of just v-if="classes".
v-if="classes" will always be true
v-if="classes.length > 0" will be true when the Array has more the 0 elements in it
Why
Because of the asynchronous nature of the API request, the moment the form tries to render this.classes will still be the empty Array you defined. Only later, once the API request has finished, this.classes will have the data it needs.
empty arrays are truthy, so v-if="classes" will always be true. use classes.length, as an empty array will result in 0 which is falsy.
maybe yo can do something like
<div v-if="classes.length>0">
{{classes.data.response}}
</div>
Hi I'm using Vuejs to get some pokemon data. So I figured out how to retrieve all the pokemon name and their api urls to get more information about them. The issue is I don't know how to take those URLs and access each pokemon's specific data. I tried to increment a variable and concatenate it to the URL to get their data but it didn't work. I also tried to access the data from the api call I already but that also didn't work.
<template>
<div>
<h2>{{subtitle}}</h2>
<div v-for="pokemon in basicInfo" v-bind:key="pokemon.name">
<span>{{ pokemon.name}}</span>
</div>
<!-- Nothing is produced, and I dont get I an error -->
<div v-for="pokemon2 in advInfo" v-bind:key="pokemon2.index">
<span>{{pokemon2}}</span>
</div>
<script>
import axios from "axios";
export default {
data() {
return {
subtitle: "First 150 pokemon",
basicInfo: [],
advInfo:[],
i:0
};
},
methods: {
// trying to increment i
getNext: function(){
this.i=i++;
}
},
mounted() {
axios
// this gets a list of the first 20 pokemon. I can get the pokemon's name and their url
.get("https://pokeapi.co/api/v2/pokemon/")
.then(response => {
this.basicInfo = response.data.results;
});
// here I'm trying to access more specific data on each pokemon by concatenating a number to the url
axios
.get("https://pokeapi.co/api/v2/pokemon/5")
.then(response => {
this.advInfo= response.data.results;
});
}
};
</script>
<style scoped>
</style>
It looks like ".../api/v2/pokemon/" produces an object with a results array, and those results contain uri's like ".../api/v2/pokemon/(some id)"
The way to combine them is as follows:
axios.get("https://pokeapi.co/api/v2/pokemon/").then(response => {
this.basicInfo = response
let promises = this.basicInfo.map(result => {
return axios.get(result.url)
})
Promise.all(promises).then(response => {
this.advInfo = response
})
});
Now advInfo will be an array, like you expect so you can render it with v-for....
<div v-for="(pokemon2, i) in advInfo" :key="i">
<pre>{{pokemon2}}</pre>
</div>
I am creating blog commenting system, I want to show comments for a post using vue.js.
In console, it says
Property or method "comment" is not defined on the instance but
referenced during render.
Also, when I try to catch user name, I got this error
Error in render: "TypeError: Cannot read property 'user' of undefined"
I want to show comments and users who commented to a particular post
in show.blade.php.
web.php
Route::get('results/{post}', 'ResultsController#show')->name('posts.show');
ResultsController
public function show(Post $post)
{
$recommended_posts = Post::latest()
->whereDate('date','>',date('Y-m-d'))
->where('category_id','=',$post->category_id)
->where('id','!=',$post->id)
->limit(7)
->get();
$posts['particular_post'] = $post;
$posts['recommended_posts'] = $recommended_posts;
//return $post->comments()->paginate(5); it returns objects
return view('posts.show',compact('posts'));
}
Comments.vue
<div class="reply-comment" :v-for="comment in comments">
<div class="user-comment" >
<div class="user">
<!--<img src="" alt="" >-->
<avatar :username="comment.user.name" :size="30" ></avatar>
</div>
<div class="user-name">
<span class="comment-name">{{ comment.user.name }}</span>
<p> {{ comment.body }} </p>
</div>
</div>
<div class="reply">
<div class="seemorecomments">
see more
</div>
<button class="reply-button">
<i class="fas fa-reply"></i>
</button>
</div>
</div>
<script>
import Avatar from 'vue-avatar'
export default {
props: ['post'],
components: {
Avatar
},
mounted() {
this.fetchComments()
},
data: () => ({
comments: {
data: []
}
}),
methods: {
fetchComments() {
axios.get(`/results/${this.post.id}`).then(({ data }) => {
this.comments = data
})
}
}
}
show.blade.php
<comments-component :post="{{ $posts['particular_post']->comments }}"></comments-component>
migration table
Schema::create('comments', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id');
$table->integer('post_id');
$table->text('body');
$table->integer('comment_id')->nullable();
$table->timestamps();
});
comment.php, I have this.
protected $with = ['user'];
You have a couple of minor issues with your Vue file that can be addressed pretty quickly.
First, you should define comments as an empty array — a collection will be returned as an array of objects to the Vue. By adding an unnecessary data property in the beginning, you are allowing the v-for loop to run in your template before the data has been retrieved.
EDIT: I'm not sure about the way you wrote this data function, so I have re-written it a way in which I'm familiar.
data() {
return {
comments: []
}
},
Second, you want to get the correct data from the response. Axios data is stored another level deep (response.data). Of course, if you are paginating the results, they are one more level deep (response.data.data).
fetchComments() {
axios.get(`/results/${this.post.id}`).then(response => {
this.comments = response.data
// or for paginated results
// this.comments = response.data.data
})
}
EDIT: Thank you for providing the Gist! I think I'm seeing things more clearly now.
Update your controller like so:
You want to load the comments into the post here.
public function show(Post $post)
{
$recommended_posts = Post::latest()
->whereDate('date','>',date('Y-m-d'))
->where('category_id','=',$post->category_id)
->where('id','!=',$post->id)
->limit(7)
->get();
// load the post comments here
$post->load('comments');
$posts['particular_post'] = $post;
$posts['recommended_posts'] = $recommended_posts;
return view('posts.show',compact('posts'));
}
And you blade like so:
Your module wants a single post, not an array of comments.
<comments-component :post="{{ $posts['particular_post'] }}"></comments-component>
And you Vue like so:
You don't actually need to use Axios at all since we've already loaded the comments.
<script>
import Avatar from 'vue-avatar'
export default {
props: ['post'],
components: {
Avatar
},
data() {
return {
comments: this.post.comments
}
},
}
</script>
nI try to fetch some userdata from a mongodb (json format) using axios.get within an vue.js application. After this, i want to visualize this data using a iteration through all user-objects within the users array. But my problem is, that every single character is a single object in this array. What i want is, that every single user-json file is one object in this array. If i have three user-objects user.length should be three.
Here the code for the axios call:
axios
.get(RL + "/users")
.then(response => {
this.users = response.data
})
.catch(e => {
this.errors.push(e);
console.log("Errors in Users: " + e);
});
And with this snipped i want to iterate through all objects, displaying the username. But user.name is always only a single character and not the whole name.
<div v-if="users">
<li v-for="user in users">
{{user.name}}
</li>
</div>
Without any plugin.
var app = new Vue({
el: '#app',
// YOUR DATA HERE
data: {
filterResult: [] // THIS IS YOUR JSON FILE
},
// READY FUNCTION HERE
created: function() {
this.filterResult = this.dataResult();
},
// YOU FUNCTION HERE
methods: {
// CALLING API
dataResult: function() {
$.getJSON('/api/feature/stores/list', function(json) {
app.results = json;
app.filterResult = json;
});
},
}
});
I am trying to get data from json file, it has just json data.
[{"id":81,"body":"There are some reason to fix the issues","created_at":"2017-11-16 11:56:47","updated_at":"2017-11-16 11:56:47"}]
I added vue-resource and properly use it as per vue syntax.
import vueResource from 'vue-resource'
Vue.use(vueResource)
In my userlist component i am trying following script
export default {
data:function(){
return {
list:[],
car:{
id:'',
body:''
}
};
},
created: function(){
this.fetchCarList();
},
methods:{
fetchCarList: function(){
this.$http.get('http://localhost:8080/api.js').then(function(response){
this.list = response.data
});
}
}
}
And this is component HTML loop
<ul id="example-1">
<li v-for="item in list">
{{ item.body }}
</li>
</ul>
I have checked http://localhost:8080/api.js which is properly returning the data. Also when I am adding the json data in fetchCarList method then loop works fine but with get() call it does not working.
How can I solve the issue?
You have a scoping issue: this within the callback does not refer to your Vue instance. That is because you are not using ES6 arrow function, i.e.:
this.$http.get('http://localhost:8080/api.js').then(response => {
this.list = response.data
});
...which means the outer this is not passed in. You will have to proxy that yourself, i.e. var self = this on the outside, and then use self.list = response.data:
var self = this;
this.$http.get('http://localhost:8080/api.js').then(response => {
self.list = response.data
});