引用 https://segmentfault.com/a/1190000009404727?utm_source=tag-newest
1、安装
npm install vuex --save
2、main.js 中引入
import vuex from 'vuex'
Vue.use(vuex);
var store = new vuex.Store({//store对象
state:{
show:false
}
})
3、 在实例化 Vue对象时加入 store 对象
new Vue({
el: '#app',
router,
store,//使用store
template: '<App/>',
components: { App }
})
4、在 src 目录下 , 新建一个 store 文件夹 , 然后在里面新建一个 index.js :
import Vue from 'vue'
import vuex from 'vuex'
Vue.use(vuex);
export default new vuex.Store({
state:{
show:false
}
})
5、
mapState、mapGetters、mapActions
有时store.dispatch('switch_dialog') 这种写法很冗长 , 不方便 , 我们没使用 vuex 的时候 , 获取一个状态只需要 this.show , 执行一个方法只需要 this.switch_dialog 就行了 , 使用 vuex 使写法变复杂了 ?
使用 mapState、mapGetters、mapActions 就不会这么复杂了
以 mapState 为例 :
<template>
<el-dialog :visible.sync="show"></el-dialog>
</template>
<script>
import {mapState} from 'vuex';
export default {
computed:{
//这里的三点叫做 : 扩展运算符
...mapState({
show:state=>state.dialog.show
}),
}
}
</script>
等于
<template>
<el-dialog :visible.sync="show"></el-dialog>
</template>
<script>
import {mapState} from 'vuex';
export default {
computed:{
show(){
return this.$store.state.dialog.show;
}
}
}
</script>
注:mapGetters、mapActions 和 mapState 类似 , mapGetters 一般也写在 computed 中 , mapActions 一般写在 methods 中。