VueX安裝及使用基礎教程
1、安裝vuex依賴包
npm install vuex --save
2、導入vuex包
import Vuex from 'vuex' Vue.use(Vuex)
3、創(chuàng)建 store 對象
export default new Vuex.Store({ // state 中存放的就是全局共享的數(shù)據(jù) state: { count: 0 } })
4、將 store 對象掛載到vue實例中
new Vue({ el: '#app', render: h => h(App), router, // 將創(chuàng)建的共享數(shù)據(jù)對象,掛載到 Vue 實例中 // 所有的組件,就可以直接用 store 中獲取全局的數(shù)據(jù)了 store })
Vuex 是一個專為 Vue.js 應用程序開發(fā)的狀態(tài)管理模式。它采用集中式存儲管理應用的所有組件的狀態(tài),并以相應的規(guī)則保證狀態(tài)以一種可預測的方式發(fā)生變化。
核心模塊: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 提供唯一的公告數(shù)據(jù)源,所有共享的數(shù)據(jù)都要統(tǒng)一放到 Store 的 State 中進行存儲。我們需要保存的數(shù)據(jù)就保存在這里,可以在頁面通過 this.$store.state來獲取我們定義的數(shù)據(jù)。
// 創(chuàng)建store數(shù)據(jù)源,提供唯一公共數(shù)據(jù) const store = new Vuex.Store({ state: { count: 0 } })
組件訪問 Store 中數(shù)據(jù)的第一種方式:
this.$store.state.全局數(shù)據(jù)名稱
組件訪問 Store 中數(shù)據(jù)的第二種方式:
// 1.從 vuex 中按需導入 mapState 函數(shù) import { mapState } from 'vuex'
通過剛才導入的 mapState 函數(shù),將當前組件需要的全局數(shù)據(jù),映射為當前組件的 computed 計算屬性:
// 2.將全局數(shù)據(jù),映射為當前組件的計算屬性 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 中的數(shù)據(jù)。只有 mutation里的函數(shù)才有權利去修改state中的數(shù)據(jù)。mutation非常類似于事件:每個 mutation 都有一個字符串的事件類型 (type)和 一個回調函數(shù) (handler)。但是,mutation只允許同步函數(shù),不能寫異步的代碼。
- ①只能通過 mutation 變更 Store 數(shù)據(jù),不可以直接操作 Store 中的數(shù)據(jù)。
- ②通過這種方式雖然操作起來稍微繁瑣一些,但是可以集中監(jiān)控所有數(shù)據(jù)的變化。
定義:
// 定義 Mutation const store = new Vuex.Store({ state: { count: 0 }, mutations: { add (state) { // 變更狀態(tài) state.count++ } } })
第一種觸發(fā)方式:
// 觸發(fā) mutation methods: { handleAdd () { // 觸發(fā) mutations 的第一種方式 this.$store.commit('add') } }
打開store/index.js文件,定義mutations :
mutations: { add (state) { state.count++ } }
回到 Addition.vue文件中觸發(fā):
<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按鈕,就可以看到數(shù)值變?yōu)?。
還可以在觸發(fā) mutations 時傳遞參數(shù):
// 定義 Mutation const store = new Vuex.Store({ state: { count: 0 }, mutations: { addN (state, step) { // 變更狀態(tài) state.count += step } } })
第一種觸發(fā)方式:
// 觸發(fā) 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 函數(shù) this.$store.commit('addN', this.num) } } } </script>
此時點擊+N按鈕就會每次增加2。
觸發(fā) mutations 的第二種方式:
// 1.從 vuex 中按需導入 mapMutations 函數(shù) import { mapMutations } from 'vuex'
通過剛才導入的 mapMutations 函數(shù),將需要的 mutations 函數(shù),映射為當前組件的 methods 方法:
// 2.將指定的 mutations 函數(shù),映射為當前組件的methods 函數(shù): 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秒在顯示變化后的數(shù)值。
注意:不要在mutations函數(shù)中,執(zhí)行異步操作。所以就需要用到了Action用于處理異步任務。
(3)、Actions:
Action 用于處理異步任務。
如果通過異步操作變更數(shù)據(jù),必須通過 Action,但是在 Action 中還是要通過觸發(fā) Mutation 的方式間接變更數(shù)據(jù)。
定義:
// 定義 Action const store = new Vuex.Store({ // ...省略其他代碼 mutations: { add (state) { state.count++ } }, actions: { addAsync (context) { setTimeout(() => { context.commit('add') }, 1000) } } })
第一種方式觸發(fā):
// 觸發(fā) Action methods: { handleAdd () { // 觸發(fā) actions 的第一種方式 this.$store.dispatch('addAsync') } }
打開store/index.js文件,增加一個 addAsync:
actions: { addAsync (context) { setTimeout(() => { // 在 actions 中,不能直接修改 state 中的數(shù)據(jù) // 必須通過 context.commit() 觸發(fā)某個 mutations 的函數(shù)才行 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 函數(shù) this.$store.commit('addN', this.num) }, handleAdd3 () { this.$store.dispatch('addAsync') } } } </script>
這時點擊+1 Async按鈕,可以實現(xiàn)延遲1秒后+1的功能了。
觸發(fā) actions 異步任務時攜帶參數(shù):
定義:
// 定義 Action const store = new Vuex.Store({ // ...省略其他代碼 mutations: { addN (state, step) { state.count += step }, }, actions: { addNAsync (context, step) { setTimeout(() => { context.commit('addN', step) }, 1000) } } })
觸發(fā):
// 觸發(fā) Action methods: { handleAdd () { // 在調用 dispatch 函數(shù),觸發(fā) actions 時攜帶參數(shù) this.$store.dispatch('addNAsync', 5) } }
打開 store/index.js 文件,增加一個 addNAsync:
actions: { addAsync (context) { setTimeout(() => { // 在 actions 中,不能直接修改 state 中的數(shù)據(jù) // 必須通過 context.commit() 觸發(fā)某個 mutations 的函數(shù)才行 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 函數(shù),觸發(fā) actions 時攜帶參數(shù) this.$store.dispatch('addNAsync', 5) } } } </script>
這時點擊+N Async按鈕,可以實現(xiàn)延遲1秒后+5的功能。
觸發(fā) actions 的第二種方式:
// 1.從 vuex 中按需導入 mapActions 函數(shù) import { mapActions } from 'vuex'
通過剛才導入的 mapActions 函數(shù),將需要的 actions 函數(shù),映射為當前組件的 methods 方法:
// 2.將指定的 actions 函數(shù),映射為當前組件的 methods 函數(shù) methods: { ...mapActions(['addAsync', 'addNAsync']) }
打開 store/index.js 文件,在 actions 增加一個 subAsync:
actions: { addAsync (context) { setTimeout(() => { // 在 actions 中,不能直接修改 state 中的數(shù)據(jù) // 必須通過 context.commit() 觸發(fā)某個 mutations 的函數(shù)才行 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>
這樣實現(xiàn)的效果是一樣的。
下面用同樣的思路來實現(xiàn)-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按鈕,可以實現(xiàn)延遲1秒后-3的功能。
(4)、Getters:
Getter 用于對 Store 中的數(shù)據(jù)進行加工處理形成新的數(shù)據(jù)。不會修改 state 里的源數(shù)據(jù),只起到一個包裝器的作用,將 state 里的數(shù)據(jù)變一種形式然后返回出來。
① Getter 可以對 Store 中已有的數(shù)據(jù)加工處理之后形成新的數(shù)據(jù),類似Vue的計算屬性。
② Store 中數(shù)據(jù)發(fā)生變化,Getter 包裝出來的數(shù)據(jù)也會跟著變化。
定義:
// 定義 Getter const store = new Vuex.Store({ state: { count: 0 }, getters: { showNum: state => { return '當前最新的數(shù)量是【'+ state.count +'】' } } })
使用 getters 的第一種方式:
this.$store.getters.名稱
我們可以把文字的內容刪除掉,然后用 getters 來替換:
打開 store/index.js 文件,定義getters:
getters: { showNum (state) { return '當前最新的數(shù)量是【' + state.count + '】' } }
回到 Addition.vue 文件修改:
<h3>{{$store.getters.showNum}}</h3>
此時刷新頁面,已經(jīng)變?yōu)榱?nbsp;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>
效果圖:
到此這篇關于VueX安裝及使用基礎教程的文章就介紹到這了。希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Vuepress生成文檔部署到gitee.io的注意事項及說明
這篇文章主要介紹了Vuepress生成文檔部署到gitee.io的注意事項及說明,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-09-09vue+echarts實現(xiàn)動態(tài)折線圖的方法與注意
這篇文章主要給大家介紹了關于vue+echarts實現(xiàn)動態(tài)折線圖的方法與注意事項,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2020-09-09解決vue2.0 element-ui中el-upload的before-upload方法返回false時submit(
這篇文章主要介紹了vue2.0 element-ui中el-upload的before-upload方法返回false時submit()不生效的解決方法,這里需要主要項目中用的element-ui是V1.4.3,感興趣的朋友參考下吧2018-08-08使用Vue-scroller頁面input框不能觸發(fā)滑動的問題及解決方法
這篇文章主要介紹了使用Vue-scroller頁面input框不能觸發(fā)滑動的問題,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-08-08