vue.js - 从 API 获取数据后,VueJS 不更新 DOM?
问题描述
我正在尝试创建一个关于照片列表的示例,并且在调用 API 后将数据绑定到组件时遇到了问题。
JS代码:
<script>
// photo item
Vue.component('photo-item', {
props: ['photo'],
template: `<li>{{ photo.name }}</li>`
});
// List of photos
Vue.component('photo-list', {
props: ['photos'],
template: `
<ul id="photo-list">
<photo-item v-for="photo in photos" :photo="photo"></photo-item>
</ul>`
});
new Vue({
el: "#photo_detail",
data: {
photos: []
},
created: function() {
axios
.get('/api/photos')
.then(function (response) {
this.photos = response.data; // Data existed
})
.catch(function (err) {
console.log(err);
});
}
})
</script>
HTML 代码
<main id="photo_detail">
<photo-list v-for="photo in photos" :photo="photo"></photo-list>
</main>
从 API 获取所有照片后,据我了解,变量photos
将自动绑定,VueJS 将更新 DOM。
VueJs 2.1.6
任何帮助。
谢谢!
解决方案
问题在于您的this
值在function()
其中该值的范围为axios
而不是 vue instance 。或者你可以直接(response)=>
使用this
new Vue({
el: "#photo_detail",
data: {
photos: []
},
created: function() {
var self=this;
axios
.get('/api/photos')
.then(function (response) {
self.photos = response.data; // Data existed
})
.catch(function (err) {
console.log(err);
});
}
})
推荐阅读
- java - android.widget.Toolbar 和 android.support.v7.widget.Toolbar 有什么区别?
- python - 如何按值正确地将对象传递给函数
- joomla - 有什么方法可以手动将 Joomla 中的新注册用户发送到 Mautic?
- javascript - 如何使用 JavaScript append 插入带有样式属性的选项值?
- mysql - 有没有办法通过更改连接点来运行带有 MySql 数据库的 DNN 9?
- java - 从我的所有控制器访问一个变量
- c++ - 采用 Eigen::Tensor 的函数 - 模板参数推导失败
- python - Insert SQLalchemy from dictionary
- algorithm - 计算 3D 固定关节约束中两个实体的冲量/扭矩
- linux - 如何使用由无人用户启动的 JProfiler for JVM 远程配置文件?