引用 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對(duì)象
state:{
show:false
}
})
3、 在實(shí)例化 Vue對(duì)象時(shí)加入 store 對(duì)象
new Vue({
el: '#app',
router,
store,//使用store
template: '<App/>',
components: { App }
})
4、在 src 目錄下 , 新建一個(gè) store 文件夾 , 然后在里面新建一個(gè) 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
有時(shí)store.dispatch('switch_dialog') 這種寫(xiě)法很冗長(zhǎng) , 不方便 , 我們沒(méi)使用 vuex 的時(shí)候 , 獲取一個(gè)狀態(tài)只需要 this.show , 執(zhí)行一個(gè)方法只需要 this.switch_dialog 就行了 , 使用 vuex 使寫(xiě)法變復(fù)雜了 ?
使用 mapState、mapGetters、mapActions 就不會(huì)這么復(fù)雜了
以 mapState 為例 :
<template>
<el-dialog :visible.sync="show"></el-dialog>
</template>
<script>
import {mapState} from 'vuex';
export default {
computed:{
//這里的三點(diǎn)叫做 : 擴(kuò)展運(yùn)算符
...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 一般也寫(xiě)在 computed 中 , mapActions 一般寫(xiě)在 methods 中。