VUE-VUEX的使用

 VUEX的一般結構如下:

import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
var store = new Vuex.Store({
  state: {
    // 相當於data
  },
  mutations: {
    // 相當於methods
  },
  getters: {
    //相當於filter
  }
})
import App from './App.vue'
const vm = new Vue({
  el: '#app',
  render: c => c(App),
  store // 將 vuex 創建的 store 掛載到 VM 實例上
})

使用VUEX實現下面的功能:

步驟:

1、在store中定義一個count 來記錄輸入框中的數值

state: {
    count: 0
},

2、第一個子組件通過 this.$store.state.count 來訪問這個數據

<template>
  <div>
   <h3>{{ $store.state.count }}</h3>
  </div>
</template>

3、第一個組件實現增加+和減少-操作,

注意: 如果要操作 store 中的 state 值,只能通過調用 mutations 提供的方法,才能操作對應的數據,不推薦直接操作 state 中的數據,因爲萬一導致了數據的紊亂,不能快速定位到錯誤的原因,因爲,每個組件都可能有操作數據的方法。

在store mutations 中進行+\-操作方法:

mutations: {
    increment(state) {
      state.count++
    },
    subtract(state, obj) {
      // 注意: mutations 的 函數參數列表中,最多支持兩個參數,
      //其中,參數1:是state 狀態;參數2:通過 commit 提交過來的參數,可以是對象\數組\其他類型
      state.count -= (obj.c + obj.d)
    }
  },

4、在第一個組件中通過 使用 this.$store.commit('方法名') 調用 mutations 方法,和 this.$emit('父組件中方法名')相似

<template>
  <div class="box">
    <input type="button" value="-" @click="subtract">
    <input type="text" v-model="$store.state.count">
    <input type="button" value="+" @click="add">
  </div>
</template>

<script>
export default {
  methods: {
    add() {
      this.$store.commit("increase");//調用mutation中的+方法
    },
    subtract() {
      this.$store.commit("decrease", { c: 3, d: 1 });//調用mutation中的-方法
    }
  },
};
</script>

<style lang="stylus" scoped>
.box{
  display flex
  input {
    margin 10px
    height 40px
    font-size 18px
  }
  input:not(:nth-child(2)){
    width 50px
    text-align center
  }
}
</style>

5、有時候需要對數據做一層包裝, 這時候可以使用store 的 getters,getters 只負責對外提供數據,不負責修改數據,如果想要修改 state 中的數據,請使用 mutations,和filter類似

想在第二個組件中這樣顯示   '當前最新的count值是:' count值   

 getters: {
    optCount: function (state) {
      return '當前最新的count值是:' + state.count
    }
  }

6、第二個組件中使用store  中包裝之後的數據

<template>
  <div>
    <h2>{{ $store.getters.optCount }}</h2>
  </div>
</template>
<script>
</script>
<style lang="stylus" scoped>
</style>

總結:

1、如果組件想要直接從 state 上獲取數據: 需要 this.$store.state.屬性名

2、state中的數據,不能直接修改,如果想要修改,必須通過 mutations

3、組件通過 this.$store.commit('方法的名稱', 唯一的一個參數) 來實現對 store 中 state 數據的操作

4、如果 store 中 state 上的數據, 在對外提供的時候,需要做一層包裝,那麼 ,推薦使用 getters, 如果需要使用 getters ,則用 this.$store.getters.方法名

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