Data
钩子需要同步返回.您必须将负载添加到created
或mounted
,只需将属性添加到数据/状态,这样react 性就起作用了.
Axios的数据加载需要通过一个操作触发,因为它是异步的.Mutations 需要同步运行.我已经在created
中添加了初始加载.(mounted
也可以.)
我已经使用Vuex helper mapState
将状态属性映射到组件.使用getter也可以,但mapState
更容易编写.
请看下面的演示或这fiddle.
还可以在fiddle中取消Vuex版本下面的代码注释,并对上面的应用程序进行注释,以了解Axios如何使用out Vuex,从而更好地理解.
const URL = 'https://jsonplaceholder.typicode.com/posts';
const store = new Vuex.Store({
state: {
posts: [],
loading: true
},
actions: {
loadData({
commit
}) {
axios.get(URL).then((response) => {
// console.log(response.data, this)
commit('updatePosts', response.data)
commit('changeLoadingState', false)
})
}
},
mutations: {
updatePosts(state, posts) {
state.posts = posts
},
changeLoadingState(state, loading) {
state.loading = loading
}
}
})
new Vue({
el: '#app',
computed: Vuex.mapState(['posts', 'loading']),
store,
created() {
//console.log(this.$store)
this.$store.dispatch('loadData') // dispatch loading
}
})
/*
//example with-out vuex
new Vue({
el: '#app',
data() {
return {
loading: true,
posts: [] // add posts here so reactivity is working, also undefined would be OK
}
},
created() {
//this.loading = true --> not needed already set in data
axios.get(URL).then((response) => {
// console.log(response.data, this)
this.posts = response.data
this.loading = false
})
}
})
*/
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.13/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/3.0.1/vuex.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.17.1/axios.js"></script>
<div id="app">
<div v-if="loading">
loading...
</div>
<div v-else>
<ul>
<li v-for="post in posts">
<h1>
{{post.title}}
</h1>
<p>
{{post.body}}
</p>
</li>
</ul>
</div>
</div>