Vuex的使用——快速入門


Vuex是一個專為Vue.js應用程序開發的狀態管理工具。它采用集中式存儲管理應用的所有組件的狀態,並以相應的規則保證狀態以一種可預測的方式發生變化。

一、Vue組件傳值的方式
  • 父向子組件傳值:父組件v-bind(縮寫:)屬性綁定,子組件props接收
  • 子向父組件傳值:子組件$emit觸發,父組件v-on(縮寫@)事件綁定
  • 兄弟組件之間數據共享:EventBus
二、關於Vuex

Vuex是適用於在Vue項目開發時使用的狀態管理工具。如果一個項目開發中頻繁的使用組件傳參的方式來同步data的值,一旦項目變得很龐大,管理和維護這些值將是非常復雜的工作。Vue為這些被多個組件頻繁使用的值提供了一個統一管理的工具——Vuex。在項目中,我們只需把這些值定義在Vuex中,就可以在Vue項目的組件中使用。

三、Vuex的安裝

1.下載vuex: npm install vuex --save
2.在項目根目錄下新建一個store文件夾,在文件夾內新建index.js,初始化Vuex:

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

const store = new Vuex.Store({
  state: {count: 1000}
})

export default store;

3.將store掛載到vue實例中,在main.js中添加:

import Vue from 'vue';
import store from './store/index'
import App from './App.vue';
import router from './router';

Vue.config.productionTip = false;


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

4.在組件中使用vuex
(1)將state中定義的count拿來在h1標簽中顯示:

<template>
    <div id='app'>
        <h1>{{ $store.state.count}}</h1>
    </div>
</template>

(2)或者要在組件方法中使用:

  created() {
    console.log(this.$store.state.count)          // 打印出1000
  }
四、Vuex的核心概念
4.1 核心概念的描述
  • State:存儲應用狀態數據的對象,與vue中data類似
  • Getters:類似vue的計算屬性,store中數據的變化,getters的數據也會發生變化
  • Mutations: 提交mutation來修改store中的狀態,同步操作
  • Actions:與mutations類似,提交修改state的行為,處理異步任務(提交的是mutation,不是直接修改狀態)
  • Modules: 模塊化狀態管理,為了開發大型項目,方便狀態管理而使用的
4.2 工作流程

image

  • 首先,vue組件調用某個Vuex的方法過程中需要向后端請求時或者出現異步操作時,需要dispatch Vue中的actions方法,以保證數據的同步。actions的存在是為了讓mutations中的方法能在異步操作中起作用。
  • 如果沒有異步操作,我們可以直接在組件內提交狀態中的mutations里自己編寫的方法來完成對state成員的操作。不建議在組件中對state直接進行操作(如:ths.$store.count = 1)。這樣的話不能被VueDevtools所監控到。
  • 最后被修改后的state成員會被渲染到組件的原位置當中去。
4.2.1 mutations

(1)定義mutations

const store = new Vuex.Store({
  state: {
    count: 1000
  },
  mutations: {
    add(state,step){
      // 變更狀態
      state.count += step;
    }
  }
})

export default store;

(2)觸發mutations

  methods: {
    changeEvent() {
      // 觸發mutations,可以通過mutations傳遞參數
      this.$store.commit('add',5);
    }
  }

點擊按鈕如下:
image

4.2.2 actions

用於處理異步任務。
(1)定義actions

const store = new Vuex.Store({
  state: {
    count: 1000
  },
  mutations: {
    // 只有 mutations 中定義的函數,才有權利修噶 state 中的數據
    add(state,step){
      // 變更狀態
      state.count += step;
    }
  },
  actions: {
    addAsync(context,step) {
      setTimeout(() => {
        context.commit('add',step)
      },3000)
    }
  }
})

export default store;

(2)觸發actions

      this.$store.dispatch('addAsync',5);

點擊異步按鈕延時數據才會變化:
image

4.2.3 getters

Getter 用於對 Store 中的數據進行加工處理形成的新的數據。

  1. Getter類似vue的計算屬性
  2. Store中數據的變化,Getter的數據也會發生變化
    (1)定義getters
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);

const store = new Vuex.Store({
  state: {
    count: 1000
  },
  mutations: {
    // 只有 mutations 中定義的函數,才有權利修噶 state 中的數據
    add(state,step){
      // 變更狀態
      state.count += step;
      // 不要在mutations函數里,執行異步代碼
      // setTimeout(() => {
      //   state.count++
      // }, 3000)
    }
  },
  actions: {
    addAsync(context,step) {
      setTimeout(() => {
        context.commit('add',step)
      },3000)
    }
  },
  getters: {
    showNum: state => {
      return `當前的新數據是【${state.count}】`
    }
  }
})

export default store;

(2)使用getters

 <template>
  <div class="content">
    <img alt="Vue logo" src="../assets/logo.png">
    <div>當前最新count值:{{$store.state.count}}</div>
    <div>getters: {{$store.getters.showNum}}</div>
    <button @click="changeEvent1">觸發同步按鈕</button>
    <button @click="changeEvent2">觸發異步按鈕</button>
  </div>
</template>
<script>
export default {
  name: 'Content',
  methods: {
    // 觸發mutations,可以通過mutations傳遞參數
    changeEvent1(){
      this.$store.commit('add',5);
    },
    // 調用dispatch觸發actions時攜帶參數
    changeEvent2() {
      this.$store.dispatch('addAsync',5);
    }
  }
}
</script>

頁面顯示:
image


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM