數(shù)據(jù)存放在state里面,如何去改變數(shù)據(jù)Mutation,什么時間去改變,怎么改變action
Vuex 是一個專為 Vue.js 應用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲管理應用的所有組件的狀態(tài),并以相應的規(guī)則保證狀態(tài)以一種可預測的方式發(fā)生變化.Vuex是處理多個組件共享狀態(tài)state的問題,包括多個試圖依賴于同一個狀態(tài)、來自不同視圖的行為需要變更同一狀態(tài)。

image.png
如圖,其中state是保存狀態(tài)的地方,mutations是如何改變這寫狀態(tài),actions是什么時間去觸發(fā)mutation。
簡單的一個例子說明:
首先在app.vue同級目錄創(chuàng)建一個store.js文件,這個文件就是vuex處理數(shù)據(jù)的地方。
store.js 文件注釋說明在代碼中
// 導入vue和vuex
import Vue from 'vue'
import Vuex from 'vuex'
// 使用vuex組件
Vue.use(Vuex)
// 添加一個state,存放狀態(tài)值
const state = {
count: 1
}
// 添加mutations,對狀態(tài)值進行操作,這里做++和--操作
const mutations = {
increment(state) {
state.count++
},
decrement(state) {
state.count--
}
}
// 添加actions,外部關聯(lián)觸發(fā)mutation
const actions = {
increment: ({ commit }) => {
commit('increment')
},
decrement: ({ commit }) => {
commit('decrement')
}
}
// 導出定義的state,mutations,actions
export default new Vuex.Store({
state, mutations, actions
})
那如何使用定義的vuex相關屬性呢。首先要在main.js里面導入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')
接下來就是在組件中使用這個store。創(chuàng)建一個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中注冊了store,這里需要引用store里面state的值,則可以寫成
$store.state.count
運行結果:

image.png
針對上面對count值的改變,如果是一個頁面的數(shù)據(jù)改變,那么在 data里面也是可以實現(xiàn)的。那多個頁面使用單個state的話,會導致數(shù)據(jù)臃腫,代碼的可讀性差,多個頁面怎么使用state呢?下篇會介紹module使用,來解決這個問題。