Vuex 的作用与使用详细步骤
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式,通俗来讲就是一个管理数据的公共仓库
Vuex首页的创建
1. 新建store文件夹 新建 index.js
2. import Vue from 'vue' import Vuex from 'vuex'
3. Vue.use(Vuex)
4.创建vuex实例
const store = new Vuex.Store({
modules : {
属性名 : 导入的模块仓库
}
})
5.导出Vuex实例
export default store
6.在main.js
import store from 'vuex实例的路径'
挂载到vue实例上
new Vue ({
render : h => h(App),
store
}).$mount('#app')
2.具名模块仓库的创建与使用
1. 在store文件夹中创建 具名模块仓库 例 :cart.js
export default {
//必写的属性
namespaced:true,
state(){
retuen {
// state中和vue中的data功能和写法一致
list:[],
a:'',
b:{}
}
}
,mutations:{
// mutations 里定义函数用来修改state中的值
函数名 ( state , payload ) {
// state 第一个参数可以用来调用state中的值
// payload 第二个参数是其他地方调用传的参数
}
}
,actions : {
// action 定义函数用来与后台发送请求获取数据
函数名 ( ctx ) {
// ctx 指执行上下文
通过ctx可以调用mutations state getters 中的方法或者属性
}
}
getters : {
//用来定义计算属性的 和vue中的计算属性写法一致
计算属性名 (state) {
return 通过state来调用state中的数据
}
}
}
使用辅助函数进行使用时 按需导入 例:
import {mapState , mapMutations , mapActions , mapGetters} from 'Vuex'
...mapState('模块名' , ['要调用的属性名'])
...mapMutations ( '模块名' , ['要调用的函数名'] )
...mapActions ('模块名' , ['函数名'] )
...mapGetters ('模块名' ,['计算属性名'])
直接使用无需导入 直接使用
state使用 this.$store.state.模块名.属性
mutations使用 this.$store.commit ('模块名/函数名 ' )
actions使用 this.$store.dispatch ('模块名/函数名 ')
getters this.$store.getters['模块名/函数名 ']