數(shù)據(jù)存放在state里面,如何去改變數(shù)據(jù)Mutation肺蔚,什么時(shí)間去改變煌妈,怎么改變action
Vuex 是一個(gè)專(zhuān)為 Vue.js 應(yīng)用程序開(kāi)發(fā)的狀態(tài)管理模式。它采用集中式存儲(chǔ)管理應(yīng)用的所有組件的狀態(tài)宣羊,并以相應(yīng)的規(guī)則保證狀態(tài)以一種可預(yù)測(cè)的方式發(fā)生變化.Vuex是處理多個(gè)組件共享狀態(tài)state
的問(wèn)題璧诵,包括多個(gè)試圖依賴(lài)于同一個(gè)狀態(tài)、來(lái)自不同視圖的行為需要變更同一狀態(tài)段只。
如圖腮猖,其中state是保存狀態(tài)的地方,mutations是如何改變這寫(xiě)狀態(tài)赞枕,actions是什么時(shí)間去觸發(fā)mutation澈缺。
簡(jiǎn)單的一個(gè)例子說(shuō)明:
首先在app.vue同級(jí)目錄創(chuàng)建一個(gè)store.js文件坪创,這個(gè)文件就是vuex處理數(shù)據(jù)的地方。
store.js 文件
注釋說(shuō)明在代碼中
// 導(dǎo)入vue和vuex
import Vue from 'vue'
import Vuex from 'vuex'
// 使用vuex組件
Vue.use(Vuex)
// 添加一個(gè)state姐赡,存放狀態(tài)值
const state = {
count: 1
}
// 添加mutations莱预,對(duì)狀態(tài)值進(jìn)行操作,這里做++和--操作
const mutations = {
increment(state) {
state.count++
},
decrement(state) {
state.count--
}
}
// 添加actions项滑,外部關(guān)聯(lián)觸發(fā)mutation
const actions = {
increment: ({ commit }) => {
commit('increment')
},
decrement: ({ commit }) => {
commit('decrement')
}
}
// 導(dǎo)出定義的state依沮,mutations,actions
export default new Vuex.Store({
state, mutations, actions
})
那如何使用定義的vuex相關(guān)屬性呢。首先要在main.js里面導(dǎo)入store.js枪狂,然后初始化store危喉。代碼:
import Vue from 'vue'
import App from './App.vue'
import store from './store'
Vue.config.productionTip = false
new Vue({
render: h => h(App),
store
}).$mount('#app')
接下來(lái)就是在組件中使用這個(gè)store。創(chuàng)建一個(gè)vue-x.vue文件
<template>
<div>
<div class="vuex">vuex {{$store.state.count}}</div>
</div>
</template>
<script>
import { mapActions } from "vuex";
export default {
methods: mapActions(["increment", "decrement"])
};
</script>
<style lang="stylus"></style>
由于main.js中注冊(cè)了store州疾,這里需要引用store里面state的值辜限,則可以寫(xiě)成
$store.state.count
運(yùn)行結(jié)果:
針對(duì)上面對(duì)count
值的改變,如果是一個(gè)頁(yè)面的數(shù)據(jù)改變严蓖,那么在 data
里面也是可以實(shí)現(xiàn)的薄嫡。那多個(gè)頁(yè)面使用單個(gè)state的話(huà),會(huì)導(dǎo)致數(shù)據(jù)臃腫颗胡,代碼的可讀性差毫深,多個(gè)頁(yè)面怎么使用state呢?下篇會(huì)介紹module
使用毒姨,來(lái)解決這個(gè)問(wèn)題哑蔫。