1.1基本使用:
安装:npm install vuex --save
导入:import Vuex from 'vuex'
注册:Vuex.use(Vuex)
创建store对象:
const store = new Vuex.Store({
state:{count:0} //state中存放的是全局共享的数据
})
挂载:
挂载store到vue实例中(在main.js中挂载与router平级)
1.2(state)
用来访问store\index.js中的数据:
方式①:this.$store.state.count //(在模板中访问时,this可以省略) 不常用
方式②:从vuex中按需导入mapState函数,然后映射为当前组件的computed计算属性
import { mapState } from 'vuex'
--------------
computed:{
...mapState(['count'])
}
1.3(mutation)
用来修改store里的数据(触发mutation的方式)(不允许直接通过组件修改store里的数据(不能使用this.$store.state.count
这种形式修改))
方式①:
通过mutation变更store数据,虽然繁琐,但可以集中监控所有数据的变化
mutations: { //第一步 store
add(state) { //store内定义add方法;携带参数是直接在state后,写参数名step
state.count++
}
},
methods: { //第二步 组件内
handler(){ //组件内部调用store中定义的add方法
this.$store.commit('add') //“add”后可写携带的参数值
}
},
方式②:
映射函数 (将指定的matutions函数,映射为当前组建的mthods函数)
mutations: { //第一步 store
sub(state) { //store内定义add方法;携带参数是直接在state后,写参数名step
state.count++
}
},
import {mapMutations}from Vuex
methods:{
...mapMutations(['sub'])//addN为参数
handler(){ this.sub(3) }
}
1.4 (action)
因为mutation不能处理异步操作,所以action用来处理异步操作,但在action中是通过触发mutation的方式间接修改数据
方式①:
actions:{
addAsync(context,step){ //step为携带参数
setTimeout(() => {
context.commit('add',step) //通过context.commit间接调用mutations中的某个方法才行
},1000)
}
}
methods: {
hand3(){
//dispatch函数用来触发actions函数
this.$store.dispatch('addSync',5) //5为参数值
}}
方式②:
actions:{
addSync(context, step) {
setTimeout(() => {
context.commit('jiafa', step)
}, 1000)
}},
import {mapActions} from "vuex"
mathods:{
...mapActions(['addSync']),
jia(){
this.addSync(5)//5为参数
}
1.4 (getter)
①getter可以对store中已有的数据加工处理之后形成新的数据(类似计算属性)
②store中的数据发生变化,gettter的数据也会发生变化。
// 在store/index.js中定义getters:
getters: {
showNum(state) { //可以使用箭头函数
return '当前的count的值为 [' + state.count + '] (我是getter方法(属性))'
}
},
方式一:
在组件内直接调用getters方法(属性)
<h4>{{ this.$store.getters.showNum }}</h4>
方式二:
把getters属性映射到computed计算属性中
import {mapGetters} from ‘vuex’
computed:{
...mapGetters(['showNum'])
} //映射之后可以直接使用 {{showNum }}进行绑定使用
1.5(module)
与模块有关,用于模块化分隔;
vuex允许我们将store划分为模块,不至于store过于臃肿; modules 中则是我们自定义注册的module. 每个module 中都有自己独立的state, action, mutation, getter文件。
谢谢浏览!