VueX 基礎(state/mutation/action)

數(shù)據(jù)存放在state里面,如何去改變數(shù)據(jù)Mutation,什么時間去改變,怎么改變action

vueX

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使用,來解決這個問題。

最后編輯于
?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容