异步管理数据就是有发请求,我们这里异步请求用axios,这个也是第三方的库,所以我们要在当前项目yarn add axios或者npm i axios,然后再store.js文件里面导入
import axios from 'axios'
在来到组件文件里面的template组件这里添加一个事件触发源
获取电影
然后再export default这里派发一个action
clickHandler: function () {
// 获取异步数据 希望通过仓库进行 异步数据的管理
this.$store.dispatch('getMovie'); // 派发 action 。 同步:commit,异步 action
}
然后异步请求不能在store.js的 mutations里面修改数据咯,要在const store = new Vuex.Store先加一个action
actions: {
getMovie: function (store, payload) {
var url = 'https://movie.52kfw.cn/index.php/Api/Movie/alst?page=1&size=20';
axios.get(url).then(response => {
console.log(response);
if( response.status === 200 && response.data.error_code === 0 ){
// 把返回的数据交给仓库里面的 state 里面的 movieData
// response.data.result;
// 当前 store 对象
store.commit('saveMovieData', response.data.result);
}
}).catch( error => {
console.log(error);
})
console.log('getMovie');
}
},
如上里面也有 store.commit('saveMovieData', response.data.result);response.data.result就是要传过去的payload值
因为把返回的数据交给仓库里面的 state 里面的 movieData,所以事先要在state里面定义一下
state: