vuex介绍
vuex是专门为vue.js设计的状态管理模式。vuex应用的核心是store,store包含了应用中的大部分状态。可以理解为其就是一个“前端数据库”,让其在各个页面上实现数据的共享。简单来说就是实现组件间的数据同步,不需要通过prop这样的繁琐的方式来修改组件间的数据。
网上的大多数博客都把vuex写得很复杂,而且vue-cli的版本都比较老,配置有一些出入,跟着做比较困难。所以我总结了一篇比较简单易懂vuex使用。
安装和全局使用
我们先用npm在目标文件中安装vuex
npm install vuex -D
接着我们需引入并使用vuex插件, 创建一个组件间共享的store对象,然后注册使用store
修改配置./src/main.js文件如下:
import vuex from 'vuex'//引入vuex
Vue.use(vuex); //使用vuex插件
var store = new vuex.Store({//创建一个共享的store对象
state:{
show:false
}
})
new Vue({
el: '#app',
router,
store,//注册使用store
template: '<App/>',
components: { App }
})
完成这些 ,我们就可以在组件中使用show这个变量了,引用方式为$store.state.show。
我们在不同组件中引用$store.state.show,只要有一个组件修改其的值,其他组件都会同步修改,这用起来有点像组件间的全局变量。
modules
如果我们把全部store写在上面不利于日后的维护,我们可以在./src下创建一个store文件夹专门用来存储store。
import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex);
export default new vuex.Store({
state:{
show:false
}
})
当然./src/main.js中的代码也要作出相应修改
import store from './store'
new Vue({
el: '#app',
router,
store,//使用store
template: '<App/>',
components: { App }
})
这样我们就可以将store单独分离出一个文件,但不同的组件都放在同一个文件中,显然不是一个很好的选择,所以,我们可以利用vuex提供的modules模块,将不同用处的store再区分开。
import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex);
import dialog_store from '../components/dialog_store.js';//引入某个store对象
export default new vuex.Store({
modules: {
dialog: dialog_store
}
})
这样我们在./src/components下创建一个dialog_store.js文件存放相应的store
export default{
state:{
show:false
}
}
我们在引用的时候就需要修改一下为$store.state.dialog.show即可。
注:引用的时候不是$store.dialog.state.show
mutations
当我们的要进行多个操作,修改state的状态时(例如对某数据进行加减操作),我们就可以使用vuex提供的mutations。(官方建议定义的方法使用全大写)
export default {
state:{//state
count:0
},
mutations:{
INCREMENT(state){//这里的state对应着上面这个state
state.count++;
},
DECREMENT(state) {
state.count--
}
}
}
接着我们需要使用\store.commit()来触发mutations定义的方法。
<template>
<div id="app">
<a href="javascript:;" @click="$store.commit('INCREMENT')">点击</a>
<t-dialog></t-dialog>
</div>
</template>
<script>
import dialog from './components/dialog.vue'
export default {
components:{
"t-dialog":dialog
}
}
</script>
注:mutation里方法必须是同步的。
当然我们还可以传入一个参数,来实现条件修改,各种骚操作得看你的脑洞有多大。
mutations:{
increment(state,n){
state.count += n;
}
}
//调用increment方法
$store.commit('increment',10);
actions
actions的用法很简单,其实就是用来触发多个mutations事件的
export default {
state:{//state
show:false
},
mutations:{
switch_dialog(state){//这里的state对应着上面这个state
state.show = state.show?false:true;
//你还可以在这里执行其他的操作改变state
}
},
actions:{
switch_dialog(context){//这里的context和我们使用的$store拥有相同的对象和方法
context.commit('switch_dialog');
//你还可以在这里触发其他的mutations方法
},
}
}
而使用则是使用$store.dispatch(‘switch_dialog’)"用法和mutations大同小异。
getters
getters有点类似于vue中的computed属性,都是用来计算state。其和mutations还是有很大的区别的,mutations是用来修改公共状态的,而getters是用来计算状态,返回不同的状态,并没有真正修改到公共状态。
export default {
state:{
count:0,
show:true
},
getters:{
not_show(state){
return !state.show;
}
}
}
我们要在组件中引用not_show状态,可以这样$store.getters.not_show。
注意$store.getters.not_show的值不能直接修改。
这仅是一些常用用法,更多详细用法可以参考官方文档 vuex官方文档