天天看點

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')