一、Vuex簡(jiǎn)述
Vuex其實(shí)就是一個(gè)狀態(tài)管理工具,所謂的狀態(tài),就是數(shù)據(jù),通過(guò)這個(gè)工具進(jìn)行管理某些數(shù)據(jù)。當(dāng)多個(gè)組件都需要同一個(gè)數(shù)據(jù)時(shí),可以將這個(gè)數(shù)據(jù)交給Vuex進(jìn)行統(tǒng)一的管理,組件可以直接引用這個(gè)數(shù)據(jù),避免了組件間繁瑣的層層傳遞的情況。
二、Vuex核心
Vuex有五大核心,state,getter,mutation,action,module。state用來(lái)存放要被管理的數(shù)據(jù),getter相當(dāng)于computed計(jì)算屬性,mutation中用來(lái)定義要修改state中數(shù)據(jù)的方法,action中用來(lái)定義異步的一些方法,module可以將多個(gè)store分成一個(gè)一個(gè)的模塊。
三、Vuex使用
- 在vue項(xiàng)目中使用Vuex時(shí),需要先安裝Vuex插件,并且注冊(cè),一般情況下都會(huì)在,在src下新創(chuàng)建一個(gè)store文件夾,下邊有一個(gè)index.vue,在這個(gè)文件中創(chuàng)建store容器實(shí)例.。
// 1. 安裝插件
npm install vuex --save
// 2. 注冊(cè)插件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
- 創(chuàng)建vuex實(shí)例,在vuex上提供了一個(gè)Store()方法,用來(lái)創(chuàng)建實(shí)例,將其命名為store,意為倉(cāng)庫(kù)的意思。在Vuex.Store()中傳一個(gè)配置對(duì)象,配置對(duì)象中包括上述的五大核心,如果用不到,也可以不做配置。
const store = new Vuex.Store({
state: {num: 2}, // 存放數(shù)據(jù)
getters: {}, // 計(jì)算屬性
mutations: {}, // 修改state中數(shù)據(jù)的一些方法
actions: {}, // 異步方法
modules: {} // store模塊
})
export default store
- 在入口文件main.js中引入store。
// main.js
import Vue from 'vue'
import App from './App'
import store from './store/index.vue' // 簡(jiǎn)寫(xiě) import store from './store'
Vue.config.productionTip = false
new Vue({
el: '#app',
store: store, // es6 簡(jiǎn)寫(xiě) 直接寫(xiě) store 屬性名和變量名相同
render: h => h(App)
})
- 在頁(yè)面中如何使用store中的數(shù)據(jù)?在使用vuex中的數(shù)據(jù)之前,先使用import導(dǎo)入寫(xiě)好的store。組件中在插值表達(dá)式中使用$store.state.num獲取store中num的數(shù)據(jù)。
<template>
<div>
<h2>{{ $store.state.num }}</h2>
</div>
</template>
四、mapState,mapMutations,mapGetters,mapActions映射
1. // 先從vuex中結(jié)解構(gòu)出四個(gè)方法
import {mapState, mapMutations, mapGetters, mapActions} from 'vuex'
2. // 在computed計(jì)算屬性中映射state數(shù)據(jù)和getters計(jì)算屬性
computed: {
...mapState('模塊名', ['name', 'age'])
...mapGetters('模塊名', ['getName'])
}
3. // 在methods方法中映射mutations和actions方法
methods: {
...mapMutations('模塊名', ['方法名1','方法名2'])
...mapActions('模塊名', ['方法名1','方法名2'])
}
4. 這些數(shù)據(jù)和方法都可以通過(guò)this來(lái)調(diào)用和獲取
以上就是vuex大致的使用方法
全文轉(zhuǎn)自: 辰漪博客