Vuex

小型項目

Vuex 是一個全局數據管理器;

不過小項目的話可以不用 Vuex ;直接使用根組件保存用戶數據;(因爲每一個組件都可以訪問到根組件)

大型項目的話就得使用 Vuex 來管理數據了;



開始

每一個 Vuex 應用的核心就是 store(倉庫)。“store”基本上就是一個容器,它包含着你的應用中大部分的狀態 (state)。Vuex 和單純的全局對象有以下兩點不同:

  1. Vuex 的狀態存儲是響應式的。當 Vue 組件從 store 中讀取狀態的時候,若 store 中的狀態發生變化,那麼相應的組件也會相應地得到高效更新。

  2. 你不能直接改變 store 中的狀態。改變 store 中的狀態的唯一途徑就是顯式地提交 (commit) mutation。這樣使得我們可以方便地跟蹤每一個狀態的變化,從而讓我們能夠實現一些工具幫助我們更好地瞭解我們的應用。



使用

安裝

> npm i vuex

配置
創建文件 src/store.js

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(vuex)

const store = new Vuex.Store({
    // 數據源
    state: {
        count: 0
    },
    
    // 修改數據的方法,第一個參數是 state對象
    mutations: {
        change(state){
            state.count++;
        }
    },
    
    // 查詢數據,第一個參數是 state對象
    getters: {
        getCount(state){
            return state.count;
        }
    },
    
    actions: { }
})

export default store;

main.js

import store from './store'
new Vue({
  render: h => h(App),
  store
}).$mount('#app')

使用

讀取 getters 的數據:

// this.$store.getters.方法名
// 如:
this.$store.getters.getCount

調用 mutation 中的方法修改數據

// commit()  用來觸發 mutation 中的函數
// commit('函數名稱', 自定義參數)
this.$store.commit('change')

action中的函數
第一個參數:context 實際上就是一個 store對象,之前通過 $store.commit來調用 mutation中的函數來修改數據

$store 就是一個 store對象,可以通過 commit 調用函數
而這裏的 context也是這個對象,所以也可以通過 commit 調用函數

// 定義
// 第一個參數:context 實際上就是一個 store對象
// 第二個參數:自定義參數
actions: {
    CHANGE_COUNT(context){
        console.log(context)
    }
}
// 使用
// dispatch()  用來觸發 action中的函數
// dispatch('函數名稱', 自定義參數)
this.$store.dispatch('CHANGE_COUNT')

通過 action 來修改數據
首先在 action中調用mutation中修改數據的方法

actions: {
    CHANGE_COUNT(context, '自定義參數 可選'){
    
    	// context: store 對象
    	// 可以通過 commit 來修改數據
    	// 可以通過 getters 來查詢數據
    	// 可以通過 dispatch 來訪問 actions
        const {commit, dispatch, getters} = context;
        
		// commit(函數名, 自定義參數)
        commit('change')
    }
}
// 調用 action中的函數
// this.$store.dispatch( 函數名, 自定義參數)

this.$store.dispatch('CHANGE_COUNT')
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章