TypeError: Cannot set property 'posts' of undefined - Vuejs
TypeError: Cannot set property 'posts' of undefined - Vuejs
我使用 VueJs 和 Laravel 创建 SPA。
主页我通过 api laravel 获取所有帖子并且 axio responsive 有数据对象。
但是我无法更新帖子 属性.
- chrome 调试工具出错:
我的代码在Wellcome.vue
import { mapGetters } from 'vuex'
import axios from 'axios'
export default {
name: 'welcome',
layout: 'default',
metaInfo: { titleTemplate: 'Welcome | %s' },
computed: mapGetters({
authenticated: 'authCheck'
}),
data: () => ({
title: 'Demo Blog',
}),
props: {
posts: {
type: Object
}
},
created () {
axios.get('/api/posts')
.then(function (response) {
this.posts = response.data;
})
.catch(function (error) {
console.log(error);
});
},
}
您正在使用常规函数作为回调,这意味着 this
引用更改。你需要在这里使用箭头功能。 () => {}
.
axios.get('/api/posts')
.then((response) => {
this.posts = response.data;
})
.catch((error) => {
console.log(error);
});
首先你在你的道具属性中定义了posts
。你不应该改变子组件的道具。道具是 One-Way-Data-Flow
您可以在您的数据 属性 中初始化 posts
,如下所示:
data(){
return{
posts: null
}
}
然后你可以通过你的API获取数据并在数据属性
中分配给你的posts
this
在你的 then
函数中没有指向 vue 实例。
所以你最好这样做
created () {
var vm = this;
axios.get('/api/posts')
.then(function (response) {
vm.posts = response.data;
})
.catch(function (error) {
console.log(error);
});
},
}
或者你像这样的 => 函数
created () {
axios.get('/api/posts')
.then( (response) => {
this.posts = response.data;
})
.catch(function (error) {
console.log(error);
});
},
}
我使用 VueJs 和 Laravel 创建 SPA。 主页我通过 api laravel 获取所有帖子并且 axio responsive 有数据对象。 但是我无法更新帖子 属性.
- chrome 调试工具出错:
我的代码在Wellcome.vue
import { mapGetters } from 'vuex'
import axios from 'axios'
export default {
name: 'welcome',
layout: 'default',
metaInfo: { titleTemplate: 'Welcome | %s' },
computed: mapGetters({
authenticated: 'authCheck'
}),
data: () => ({
title: 'Demo Blog',
}),
props: {
posts: {
type: Object
}
},
created () {
axios.get('/api/posts')
.then(function (response) {
this.posts = response.data;
})
.catch(function (error) {
console.log(error);
});
},
}
您正在使用常规函数作为回调,这意味着 this
引用更改。你需要在这里使用箭头功能。 () => {}
.
axios.get('/api/posts')
.then((response) => {
this.posts = response.data;
})
.catch((error) => {
console.log(error);
});
首先你在你的道具属性中定义了posts
。你不应该改变子组件的道具。道具是 One-Way-Data-Flow
您可以在您的数据 属性 中初始化 posts
,如下所示:
data(){
return{
posts: null
}
}
然后你可以通过你的API获取数据并在数据属性
中分配给你的posts
this
在你的 then
函数中没有指向 vue 实例。
所以你最好这样做
created () {
var vm = this;
axios.get('/api/posts')
.then(function (response) {
vm.posts = response.data;
})
.catch(function (error) {
console.log(error);
});
},
}
或者你像这样的 => 函数
created () {
axios.get('/api/posts')
.then( (response) => {
this.posts = response.data;
})
.catch(function (error) {
console.log(error);
});
},
}