VueX状态管理器
cnpm i vuex axios -S
1 创建Vuex 仓库
import Vue from 'vue'
import Vuex from 'vuex'
vue.use(Vuex)
const store = new VueX.store({
 state: {//存放状态},
 mutations:{//唯一修改状态的地方,不在这里做逻辑处理}
})
export default store
2 在入口文件main.js下引入store
import store from './store/index.js'
将store 放到根实例里 以供全局使用
new Vue({
 el:'#app',
 store,
 components:{App},
 template:<App/>
})
开始使用store(以home组件为例)Vuex的使用也是一种渐进式的,你可以从最简单的开始使用,根据经验和技术的增加,再渐进增强对它的使用,如果按照级别算vuex的使用可以从最基本的t1级别开始,先总结最基本的前三个版本,后续有时间再总结其他的。
T1级别
1.
在hoome/script.js中进行请求数据
import Vue from 'vue'
import axios from 'axios'
export default {
 mounted(){
 axios.get('请求数据的接口')
 .then((res)=>{this.$store.commit('changeList',res.data)})
 //changeList相当于调用了在store.mutations中定义的修改状态的方法
 //res.data 就是在改变状态时要修改的数据,需要在这传递过去。
 .catch((err)=>{console,log(err)})
 }
 }
2.
在store/index.js中定义
import Vue from 'vue'
import Vuex from 'vuex'
vue.use(Vuex)
const store = new VueX.store({
 state: {
 //存放状态
 list: [ ] //存放一个空的数组
},
 mutations:{
 //唯一修改状态的地方,不在这里做逻辑处理
 //定义一个修改list的方法
 //state 指上面存放list的对象,data 为在请求数据出传过来请求到的数据
 changeList (state,data) {
 state.list = data //将请求来的数据赋值给list
 }
 }
 })
export default store
3.
在home/index.vue中渲染
<template>
 //渲染数据的时候通过this.store.state.list直接从store中取数据
 //还可以从其他组件通过这种方法去用这个数据无需重新获取
 <li v-for='item of this.store.state.list' :key='item.id'>{{item.name}}</li>
</template>注意点:如果我们在home组件中获取的数据,可以在其他组件中使用,但是是当页面刷新默认进入home页,也就是相当于修改了数据,再点击其他页面也能有数据。如果我们在user组件中获取的数据要在home组件中使用,当页面刷新数据是不会显示的,因为此时还没有触发user组件中的更改数据的方法,所以数据为空,当点击user页面时,就会有数据,这个时候再去点击home页面我们就能够看到在home 组件中使用user组件中获取的数据了。解决这种问题的办法可以将数据存到本地一份或者都在首页进行请求数据
T2级别
在页面进行渲染的时候我们需要通过this.store.state去拿数据,这样的写法太长而且不太好
用计算属性结合mapState去解决这个问题
1
在home/script.js中进行操作
import Vue from 'vue'
import mapState from 'vuex'
import axios from 'axios'
export default {
 computed:{
 //mapState为辅助函数
 ...mapState(['list'])
 },
 mounted(){
 axios.get('请求数据的接口')
 .then((res)=>{this.$store.commit('changeList',res.data)})
 .catch((err)=>{console,log(err)})
 }
 }
2
在home/index.vue中渲染
<template>
 <li v-for='item of list' :key='item.id'>{{item.name}}</li>
</template>T3级别
使用常量去代替事件类型(便于查看状态,利于维护)
 1
 在store下创建mutation-type.js
 export const CHANGE_LIST = 'CHANGE_LIST'
 
 2
 在store/index.js引入mutation-type.js
 import Vue from 'vue'
 import Vuex from 'vuex'
 import {CHANGE_LIST } from‘./mutation-type.js’
 vue.use(Vuex)
 const store = new VueX.store({
 state: {
 list: [ ] //存放一个空的数组
 },
 mutations:{
 //我们可以使用Es6风格的计算属性命名功能来使用一个常量作为函数名
 [CHANGE_LIST] (state,data) {
 state.list = data //将请求来的数据赋值给list
 }
 }
 })
 export default store
 
 3
 在home/script.js中进行引入
 import Vue from 'vue'
 import mapState from 'vuex'
 import axios from 'axios'
 import {CHANGE_LIST} from ‘../../store/mutation-type.js’
 export default {
 computed:{
 //mapState为辅助函数
 ...mapState(['list'])
 },
 mounted(){
 axios.get('请求数据的接口')
 .then((res)=>{this.$store.commit(CHANGE_LIST,res.data)})
 .catch((err)=>{console,log(err)})
 }
 }相关文章推荐:
vue中权限控制动态路由的创建流程(图文)
vue指令与$nextTick操作DOM有什么区别?
下载本文