VUEX是什么?
用来解决组件之间共用数据问题的一个插件
Vuex 内部结构
State 就是被共用的数据(但是不可以被直接操作,不可以直接访问)
Mutations 可以直接操作(Mutate) State 中的数据,可以定义 State 中的数据如何被改变
Actions 可以触发 Mutations 对States的改变,该触发操作专业名词为commit
Components 与Vuex的交互
通过 dispatch Actions 的方式来改变 State
通过Render来读取State中的数据
Vuex的使用方法
新建一个store.js文件(位置可以自选)
在该文件中引入vue和vuex,并在vue中启用vuex
Improve vue from ‘vue’
Improve vuex from ‘vuex’
vue.use(vuex)
在该文件中配置 state,mutations,actions
//这里的state是数据实际储存的地方
const state={
count:10
}
const mutations={
add(state,param){
state.count += param
},
reduce(state,param){
state.count -= param
}
}
const actions={
add:({commit},param)=>{
commit(‘add’,param)
},
reduce:({commit},param)=>{
commit(“reduces”,param)
}
}
只有一个store配置的方法
将以上配置在Vuex对象中实例化并导出
export default new vuex.Store({
state,
mutations,
actions
})
在main.js中引用该vuex的store实例
improt store from ‘./store’
new vue ({
……
store,
……
})
在组件中使用vuex的store实例在页面中引用该实例state的值 $store.state.count引入该实例的actions
import {mapActions} from ‘vuex’
export default {
methods:mapActions([‘add’,’reduce’])
}
页面使用actions @click=’add(param)’ @click=’reduce(param)’
有多个store配置的方法
将以上配置在Vuex对象中实例化并导出
export default new vuex.Store({
module:{
a: {
state,
mutations,
actions
}
}
})
在main.js中引用该vuex的store实例
improt store from ‘./store’
new vue ({
……
store,
……
})
在组件中使用vuex的store实例在页面中引用该实例state的值 $store.state.a.count调用该实例的actions
import {mapActions} from ‘vuex’
export default {
methods:mapActions(‘a’,[‘add’,’reduce’])
}
页面使用actions @click=’add(param)’ @click=’reduce(param)’
这篇笔记主要是本人学习Vuex时候的知识总结,如果有不对的地方还请多多斧正
发表回复