本文共 1202 字,大约阅读时间需要 4 分钟。
不相关的多个组件想共用一份数据,Vuex可以起到关联作用
Status:存储所有组件想要共享的数据,相当于组件中的data
Mutations:直接操作status中的数据,即定义如何改变status中的数据
Actions:什么时候去改变这个数据,需要actions来触发
组件交互触发Actions,Actions提交commit来告诉Mutations在这个时候执行操作,然后改变status中的数据,改变的数据会重新渲染组件
示例:
安装vuex插件
npm i vuex --save
在src目录下创建一个store.js,写入
import Vue from 'vue'import Vuex from 'vuex'Vue.use(Vuex)const state = { count: 1}const mutations = { increment(state) { state.count++ }, decrement(state) { state.count-- },}const actions = { increment: ({commit}) => { commit('increment') }, decrement: ({commit}) => { commit('decrement') }}export default new Vuex.Store({state, mutations, actions})
在main.js中引入和使用store.js
import store from './store'new Vue({ render: h => h(App), store}).$mount('#app')
创建一个新的组件vuexx.vue,写入
$store.state.count 可以得到store中共享的数据,mapAtions起到方法关联的作用
不使用mapAtions,increament也还是方法,但它就不能关联到store下的increament的方法
高级示例:
在src目录下新建store文件夹,新建下列文件
a.js中写入
b.js中写入
index.js入口文件写入,通过模块导出这2个数据
在main.js中导入和使用index.js
然后创建2个组件 a.vue和b.vue,在父组件中引入
之后就可以在a.vue中使用和操作a.js模块中的数据,注意使用的mapActions函数会有变化,一定要指定对应的模块
b.vue也是同理
这样2个数据是相互独立的
有时我们想点击按钮后想让数据加2而不是加1,这时候我们需要传参,而且是从事件触发时开始考虑传参
add中传入一个参数2
action中继续传播这个参数2,也就是param
在mutations操作数据时就可以使用这个参数2
转载地址:http://clsuk.baihongyu.com/