之前也看了vuex的文档,对它的原理只是了解,看代码(仅自己复习、做笔记)
流程是在组件的created中提交dispatch,然后通过action调用一个封装好的axios然后再触发mutation来提交状态改变state中的数据,然后在组件的计算属性中获取state的数据并渲染在页面上。
mock.js文件 模拟user列表
/*user列表*/
Mock.mock('/api/getUserInfo','post', {
"data|10-20": [
{
"_id": /\d{9}/,
"date": Random.date('yyyy-MM-dd'),
"name": "@cname",
"address": Random.city(true),
"sex|1": [
"男",
"女"
]
}
]
})
目录结构:
fetch /api.js主要是请求数据的,这个可以看情况而定,我觉得是多余了,暂时还没有更改
用的vuex的模块化处理,这样感觉高效,适用与大型项目,这里就不一一陈述用法,就是简单的配置,然后将文件导出放在index.js文件里(出口文件?)
fetch/api.js
import axios from 'axios'
export function fetch(url,params) {
return new Promise((resolve, reject) => {
axios.post(url, params)
.then(res => {
console.log('api---ok');
console.log(res.data)
resolve(res.data)
})
.catch((error) => {
console.log(error)
reject(error)
})
})
}
export default {
getList() {
console.log('进入api.js')
return fetch('/getUserInfo') //这是我user的mock模拟的接口
}
}
userList.js
import api from './../../fetch/api'
const userList = {
state: {
userListData: [],
},
mutations: {
SET_DATELIST:(state,res) => {
console.log('进入mutations');
console.log(res)
state.userListData = res.data
console.log(state.userListData)
},
},
actions: {
getList({ commit, state }){
console.log('进入action');
api.getList().then(res =>{
console.log('axios中调用封装后的axios成功');
commit('SET_DATELIST', res)
})
}
},
getters: {}
};
export default userList
然后再页面中使用,这里我用了...Map
<template> <el-table :data="userListData" height="450" border style="width: 100%"> <el-table-column prop="_id" label="id" width="180"></el-table-column> <el-table-column prop="date" label="注册日期" width="180"></el-table-column> <el-table-column prop="name" label="用户姓名" width="180"></el-table-column> <el-table-column prop="sex" label="性别" width="180"></el-table-column> <el-table-column prop="address" label="注册地址"></el-table-column> </el-table> </template> <script> import { mapState, mapActions } from 'vuex'; export default { name: 'userList', data() { return { // userListData: [] } }, // methods:{ // getList(){ // this.$axios.post('/getUserInfo').then( res => { // console.log(res); // this.userListData = res.data // }) // } // }, // created: function () { // this. getList(); // } created() { this.$store.dispatch('getList'); //提交siapatch }, computed: { ...mapState({ userListData: state => state.userList.userListData /*从vuex中获取到数据*/ }) } } </script> <style scoped> .el-row{ margin:20px auto; } </style>
然后就可以在页面展示了,这里写这个的目的是想让自己加深对vuex触发的流程更加熟悉,里面有很多打印,可以加深理解。