gpt4 book ai didi

javascript - Vue2 对象未设置

转载 作者:太空宇宙 更新时间:2023-11-04 16:06:12 24 4
gpt4 key购买 nike

我正在尝试从服务器获取数据列表并显示它,但看起来 Vue 没有看到新数据(不让它们 react )

      Vue.component('Videos', {
template:
`
<div>
<div v-for="video in videos" v-text="video.name">
</div>
<div>
`,
data() {
return {
videos: {},
}
},
methods: {
getVideos() {
axios.get('/admin/videos?token='+localStorage.getItem('auth_token'))
.then(function(response) {
this.videos = response.data.videos;
}).catch(function(errors){
this.error = errors.data;
})
},
},
created: function () {
this.getVideos();
}

});

new Vue({
el: "#app",
});

我也尝试使用

Object.keys(response.data.videos).forEach(
key => this.$set(this.videos, key, response.data.videos[key])
);

this.videos = Object.assign({}, this.videos, response.data.videos)

但这对我来说仍然不起作用。感谢您的帮助!

最佳答案

您在 thencatch 回调中都丢失了上下文。因此,您将设置 window.videos 变量(全局),而不是组件实例 videos 属性(与 error 相同)。

简单的修复方法是使用 arrow functions保留词汇绑定(bind):

methods: {
getVideos() {
axios.get('/admin/videos?token='+localStorage.getItem('auth_token'))
.then(response => {
this.videos = response.data.videos;
}).catch(errors => {
this.error = errors.data;
})
},
},

关于javascript - Vue2 对象未设置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41851274/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com