Ben*_*Ben 3 fetch vue.js vuejs2
我的数据获取在全局使用时工作正常,但是一旦我坚持使用单个文件组件就不会返回项目。我做错了什么?
ladeditems.vue
<template>
<div>
<ul v-for="item in items">
<li>
{{item.title}}
</li>
</ul>
</div>
</template>
<script>
export default {
components: {'tiny-slider': VueTinySlider},
name: 'ladeditems',
data: {
items: null
},
methods: {
fetchData: function () {
let self = this
const myRequest = new Request('https://jsonplaceholder.typicode.com/posts')
fetch(myRequest)
.then((response) => { return response.json() })
.then((data) => {
self.items = data
// console.log(self.items)
}).catch( error => { console.log(error); });
}
},
mounted() {
this.fetchData()
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
你的data声明有误,应该是这样的:
data: function () {
return {
items: null
}
}
Run Code Online (Sandbox Code Playgroud)
这个信息在这里:数据。简而言之,它必须是一个返回对象的函数。这应该允许该属性对您的更改做出反应。
另外值得注意的是,fetch您提供的代码中没有声明,所以我假设它是一个全局声明。如果不是,并且它是一个 mixin,那么你需要将它的范围限定为this.fetch(...)