VueX 的安裝及簡單使用


1、安裝vuex依賴包

npm install vuex --save

2、導入vuex包

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

3、創建 store 對象

export default new Vuex.Store({
  // state 中存放的就是全局共享的數據
  state: {
    count: 0
  }
})

4、將 store 對象掛載到 vue 實例中

new Vue({
  el: '#app',
  render: h => h(App),
  router,
  // 將創建的共享數據對象,掛載到 Vue 實例中
  // 所有的組件,就可以直接用 store 中獲取全局的數據了
  store
})

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

核心模塊:State、Mutations、Actions、Module、Getters

在 components 目錄下新建 Addition.vue 文件:

<template>
<div>
  <h3>當前最新的Count值為:</h3>
  <button>+1</button>
</div>
</template>

Subtraction.vue 文件:

<template>
<div>
  <h3>當前最新的Count值為:</h3>
  <button>-1</button>
</div>
</template>

打開 App.vue 文件,引入倆個組件:

<template>
<div>
  <my-addition></my-addition>
  <p>------------------------------</p>
  <my-subtraction></my-subtraction>
</div>
</template>

<script>
import Addition from './components/Addition'
import Subtraction from './components/Subtraction'
export default {
  components: {
    'my-addition': Addition,
    'my-subtraction': Subtraction
  },
  data () {
    return {}
  }
}
</script>

(1)、State:

State 提供唯一的公告數據源,所有共享的數據都要統一放到 Store 的 State 中進行存儲。我們需要保存的數據就保存在這里,可以在頁面通過 this.$store.state來獲取我們定義的數據。
// 創建store數據源,提供唯一公共數據
const store = new Vuex.Store({
   state: {
      count: 0
   }
})

組件訪問 Store 中數據的第一種方式:

this.$store.state.全局數據名稱

組件訪問 Store 中數據的第二種方式:

// 1.從 vuex 中按需導入 mapState 函數
import { mapState } from 'vuex'

通過剛才導入的 mapState 函數,將當前組件需要的全局數據,映射為當前組件的 computed 計算屬性:

// 2.將全局數據,映射為當前組件的計算屬性
computed: {
    ...mapState(['count'])
}

打開 store/index.js 文件,定義 count:

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
  },
  actions: {
  },
  modules: {
  }
})

回到 Addition.vue 文件中,用第一種方式:

<template>
<div>
  <h3>當前最新的Count值為:{{$store.state.count}}</h3>
  <button @click="handleAdd">+1</button>
</div>
</template>

回到 Subtraction.vue 文件中,用第二種方式:

<template>
<div>
  <h3>當前最新的Count值為:{{count}}</h3>
  <button>-1</button>
</div>
</template>

<script>
import { mapState } from 'vuex'
export default {
  data () {
    return {}
  },
  // 計算屬性
  computed: {
    ...mapState(['count']) // 用...展開運算符把Count展開在資源屬性里
  }
}
</script>

此時效果圖:

(2)、Mutations:

Mutations 用於變更 Store 中的數據。只有 mutation 里的函數才有權利去修改 state 中的數據。mutation 非常類似於事件:每個 mutation 都有一個字符串的 事件類型 (type) 和 一個 回調函數 (handler)。但是,mutation只允許同步函數,不能寫異步的代碼

①只能通過 mutation 變更 Store 數據,不可以直接操作 Store 中的數據。
②通過這種方式雖然操作起來稍微繁瑣一些,但是可以集中監控所有數據的變化。

定義:

// 定義 Mutation
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    add (state) {
      // 變更狀態
      state.count++
    }
  }
})

第一種觸發方式:

// 觸發 mutation
methods: {
    handleAdd () {
      // 觸發 mutations 的第一種方式
      this.$store.commit('add')
    }
}

打開 store/index.js 文件,定義 mutations :

mutations: {
    add (state) {
      state.count++
    }
}

回到 Addition.vue 文件中觸發:

<template>
<div>
  <h3>當前最新的Count值為:{{$store.state.count}}</h3>
  <button @click="handleAdd">+1</button>
</div>
</template>

<script>
export default {
  methods: {
    handleAdd () {
      this.$store.commit('add')
    }
  }
}
</script>

此時點擊+1按鈕,就可以看到數值變為1。

還可以在觸發 mutations 時傳遞參數:

// 定義 Mutation
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    addN (state, step) {
      // 變更狀態
      state.count += step
    }
  }
})

第一種觸發方式:

// 觸發 mutation
methods: {
    handleAdd () {
      this.$store.commit('addN', 3)
    }
}

打開 store/index.js 文件,增加一個 addN: 

mutations: {
    add (state) {
      state.count++
    },
    addN (state, step) {
      state.count += step
    }
}

回到 Addition.vue 文件中,增加一個+N的按鈕並增加點擊事件:

<template>
<div>
  <h3>當前最新的Count值為:{{$store.state.count}}</h3>
  <button @click="handleAdd">+1</button>
  <button @click="handleAdd2">+N</button>
</div>
</template>

<script>
export default {
  data () {
    return {
      num: 2
    }
  },
  methods: {
    handleAdd () {
      this.$store.commit('add')
    },
    handleAdd2 () {
      // commit 的作用,就是調用某個 mutation 函數
      this.$store.commit('addN', this.num)
    }
  }
}
</script>

此時點擊+N按鈕就會每次增加2。

觸發 mutations 的第二種方式:

// 1.從 vuex 中按需導入 mapMutations 函數
import { mapMutations } from 'vuex'

通過剛才導入的 mapMutations 函數,將需要的 mutations 函數,映射為當前組件的 methods 方法:

// 2.將指定的 mutations 函數,映射為當前組件的methods 函數:
methods: {
   ...mapMutations({'add', 'addN'})
}

打開 store/index.js 文件,在 mutations 增加一個 sub:

mutations: {
    add (state) {
      state.count++
    },
    addN (state, step) {
      state.count += step
    },
    sub (state) {
      state.count--
    }
},

回到 Subtraction.vue 文件中,給-1按鈕增加點擊事件:

<template>
<div>
  <h3>當前最新的Count值為:{{count}}</h3>
  <button @click="handleSub">-1</button>
</div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
export default {
  data () {
    return {}
  },
  // 計算屬性
  computed: {
    ...mapState(['count']) // 用...展開運算符把Count展開在資源屬性里
  },
  methods: {
    ...mapMutations(['sub']),
    handleSub () {
      this.sub()
    }
  }
}
</script>

這時刷新頁面,點擊-1按鈕就會每次-1了。

打開 store/index.js 文件,增加一個 subN: 

mutations: {
    add (state) {
      state.count++
    },
    addN (state, step) {
      state.count += step
    },
    sub (state) {
      state.count--
    },
    subN (state, step) {
      state.count -= step
    }
},

回到 Subtraction.vue 文件中,在增加一個-N的按鈕,並添加點擊事件:

<button @click="handleSub2">-N</button>

<script>
import { mapState, mapMutations } from 'vuex'
export default {
  methods: {
    ...mapMutations(['sub', 'subN']),
    handleSub () {
      this.sub()
    },
    handleSub2 () {
      this.subN(2)
    }
  }
}
</script>

這時點擊-N按鈕,每次就-2了。

下面有個需求,就是在點擊+1按鈕后延遲1秒在顯示變化后的數值。

注意:不要在 mutations 函數中,執行異步操作。所以就需要用到了 Action 用於處理異步任務。

(3)、Actions:

Action 用於處理異步任務。

如果通過異步操作變更數據,必須通過 Action,但是在 Action 中還是要通過觸發 Mutation 的方式間接變更數據。

定義:

// 定義 Action
const store = new Vuex.Store({
  // ...省略其他代碼
  mutations: {
    add (state) {
      state.count++
    }
  },
  actions: {
    addAsync (context) {
      setTimeout(() => {
        context.commit('add')
      }, 1000)
    }
  }
})

第一種方式觸發:

// 觸發 Action
methods: {
  handleAdd () {
      // 觸發 actions 的第一種方式
      this.$store.dispatch('addAsync')
  }
}

打開 store/index.js 文件,增加一個 addAsync: 

actions: {
    addAsync (context) {
      setTimeout(() => {
        // 在 actions 中,不能直接修改 state 中的數據
        // 必須通過 context.commit() 觸發某個 mutations 的函數才行
        context.commit('add')
      }, 1000)
    }
}

回到 Addition.vue 文件中,增加一個+1 Async的按鈕並增加點擊事件:

 <button @click="handleAdd3">+1 Async</button>

<script>
export default {
  methods: {
    handleAdd () {
      this.$store.commit('add')
    },
    handleAdd2 () {
      // commit 的作用,就是調用某個 mutation 函數
      this.$store.commit('addN', this.num)
    },
    handleAdd3 () {
      this.$store.dispatch('addAsync')
    }
  }
}
</script>

這時點擊+1 Async按鈕,可以實現延遲1秒后+1的功能了。

觸發 actions 異步任務時攜帶參數:

定義:

// 定義 Action
const store = new Vuex.Store({
  // ...省略其他代碼
  mutations: {
    addN (state, step) {
      state.count += step
    },
  },
  actions: {
    addNAsync (context, step) {
      setTimeout(() => {
        context.commit('addN', step)
      }, 1000)
    }
  }
})

觸發:

// 觸發 Action
methods: {
  handleAdd () {
      // 在調用 dispatch 函數,觸發 actions 時攜帶參數
      this.$store.dispatch('addNAsync', 5)
  }
}

打開 store/index.js 文件,增加一個 addNAsync: 

actions: {
    addAsync (context) {
      setTimeout(() => {
        // 在 actions 中,不能直接修改 state 中的數據
        // 必須通過 context.commit() 觸發某個 mutations 的函數才行
        context.commit('add')
      }, 1000)
    },
    addNAsync (context, step) {
      setTimeout(() => {
        context.commit('addN', step)
      }, 1000)
    }
}

回到 Addition.vue 文件中,增加一個+N Async的按鈕並增加點擊事件:

<button @click="handleAdd4">+N Async</button>

<script>
export default {
  methods: {
    handleAdd4 () {
      // 在調用 dispatch 函數,觸發 actions 時攜帶參數
      this.$store.dispatch('addNAsync', 5)
    }
  }
}
</script>

這時點擊+N Async按鈕,可以實現延遲1秒后+5的功能。

觸發 actions 的第二種方式:

// 1.從 vuex 中按需導入 mapActions 函數
import { mapActions } from 'vuex'

通過剛才導入的 mapActions 函數,將需要的 actions 函數,映射為當前組件的 methods 方法:

// 2.將指定的 actions 函數,映射為當前組件的 methods 函數
methods: {
  ...mapActions(['addAsync', 'addNAsync'])
}

打開 store/index.js 文件,在 actions 增加一個 subAsync:

actions: {
    addAsync (context) {
      setTimeout(() => {
        // 在 actions 中,不能直接修改 state 中的數據
        // 必須通過 context.commit() 觸發某個 mutations 的函數才行
        context.commit('add')
      }, 1000)
    },
    addNAsync (context, step) {
      setTimeout(() => {
        context.commit('addN', step)
      }, 1000)
    },
    subAsync (context) {
      setTimeout(() => {
        context.commit('sub')
      }, 1000)
    }
}

回到 Subtraction.vue 文件中,在增加一個-1 Async的按鈕,並添加點擊事件:

<button @click="handleSub3">-1 Async</button>

<script>
import { mapState, mapMutations, mapActions } from 'vuex'
export default {
  methods: {
    ...mapMutations(['sub', 'subN']),
    ...mapActions(['subAsync']),
    handleSub () {
      this.sub()
    },
    handleSub2 () {
      this.subN(2)
    },
    handleSub3 () {
      this.subAsync()
    }
  }
}
</script>

還有個更簡單的方式:

<button @click="subAsync">-1 Async</button>

<script>
import { mapState, mapMutations, mapActions } from 'vuex'
export default {
  methods: {
    ...mapActions(['subAsync'])
  }
}
</script>

這樣實現的效果是一樣的。

下面用同樣的思路來實現-N的異步操作:

打開 store/index.js 文件,增加一個 subNAsync: 

actions: {
    subNAsync (context, step) {
      setTimeout(() => {
        context.commit('subN', step)
      }, 1000)
    }
}

回到 Subtraction.vue 文件中,在增加一個-N Async的按鈕:

<button @click="subNAsync(3)">-N Async</button>

<script>
import { mapState, mapMutations, mapActions } from 'vuex'
export default {
  methods: {
    ...mapActions(['subAsync', 'subNAsync'])
  }
}
</script>

這時點擊-N Async按鈕,可以實現延遲1秒后-3的功能。

(4)、Getters:

Getter 用於對 Store 中的數據進行加工處理形成新的數據。不會修改 state 里的源數據,只起到一個包裝器的作用,將 state 里的數據變一種形式然后返回出來。
① Getter 可以對 Store 中已有的數據加工處理之后形成新的數據,類似Vue的計算屬性。
② Store 中數據發生變化,Getter 包裝出來的數據也會跟着變化。

定義:

// 定義 Getter
const store = new Vuex.Store({
  state: {
    count: 0
  },
  getters: {
    showNum: state => {
      return '當前最新的數量是【'+ state.count +'】'
    }
  }
})

使用 getters 的第一種方式:

this.$store.getters.名稱

我們可以把文字的內容刪除掉,然后用 getters 來替換:

打開 store/index.js 文件,定義getters:

getters: {
    showNum (state) {
      return '當前最新的數量是【' + state.count + '】'
    }
}

回到 Addition.vue 文件修改:

<h3>{{$store.getters.showNum}}</h3>

此時刷新頁面,已經變為了 getters 中的內容,效果圖:

使用 getters 的第二種方式:

import { mapGetters } from 'vuex'

computed: {
  ...mapGetters(['showNum'])
}

打開 Subtraction.vue 文件修改:

<h3>{{showNum}}</h3>

<script>
import { mapState, mapMutations, mapActions, mapGetters } from 'vuex'
export default {
  // 計算屬性
  computed: {
    ...mapState(['count']), // 用...展開運算符把Count展開在資源屬性里
    ...mapGetters(['showNum'])
  }
}
</script>

效果圖:


免責聲明!

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



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