state 提供唯一的公共資料源,所有共享的資料都要統一放到 store 的 state 中進行儲存。建立store資料來源,提供唯一公共資料
const store =
newvuex.store(}
)
1.1 元件訪問 state 中資料的第一種方式:this
.$store.state.全域性資料名稱
1.2 元件訪問 state 中資料的第二種方式:// 1. 從 vuex 中按需匯入 mapstate 函式
import
from
'vuex'
通過剛才匯入的 mapstate 函式,將當前元件需要的全域性資料,對映為當前元件的 computed 計算屬性:
// 2. 將全域性資料,對映為當前元件的計算屬性
computed:
mutation 用於變更 store中 的資料。定義 mutation
const store =
newvuex.store(,
mutations:
,addn
(state, step)}}
)
2.1 觸發mutations的第一種方式:this.$store.commit() 是觸發 mutations 的第一種方式
methods:
,handle2()
}
2.2 觸發mutations的第二種方式:// 1. 從 vuex 中按需匯入 mapmutations 函式
import
from
'vuex'
通過剛才匯入的 mapmutations 函式,將需要的 mutations 函式,對映為當前元件的 methods 方法:
// 2. 將指定的 mutations 函式,對映為當前元件的 methods 函式
methods:
action 用於處理非同步任務。定義 action
const store =
newvuex.store(,
addn
(state, step)},
actions:
,1000)}
,addnasync
(context, step)
,1000)}
}})
3.1 觸發 action的第一種方式:methods:
,handle2()
}
3.2 觸發 action的第二種方式:// 1. 從 vuex 中按需匯入 mapactions 函式
import
from
'vuex'
通過剛才匯入的 mapactions 函式,將需要的 actions 函式,對映為當前元件的 methods 方法:
// 2. 將指定的 actions 函式,對映為當前元件的 methods 函式
methods:
getter 用於對 store 中的資料進行加工處理形成新的資料,不更改源資料定義 getter
const store =
newvuex.store(,
getters:}}
)
4.1 使用 getters 的第一種方式:this
.$store.getters.名稱
4.2 使用 getters 的第一種方式:import
from
'vuex'
computed:
/* jshint esversion: 6 */
import vue from
'vue'
import vuex from
'vuex'
vue.
use(vuex)
export
default
newvuex.store(,
getters:},
mutations:
,addn
(state, step)
,sub
(state)
,subn
(state, step)},
actions:
,1000)}
,addnasync
(context, step)
,1000)}
,subasync
(context)
,1000)}
,subnasync
(context, step)
,1000)}
}})
第一種觸發方式:
當前最新的count值為:
}<
/h3>
}<
/h3>
"btnhandler1"
>+1
<
/button>
"btnhandler2"
>+n
<
/button>
"btnhandler3"
>
+1 async<
/button>
"btnhandler4"
>
+n async<
/button>
<
/div>
<
/template>
export
default},
methods:
,btnhandler2()
,btnhandler3()
,btnhandler4()
},created()
, computed:
}<
/script>
"less" scoped>
<
/style>
第二種觸發方式:
當前最新的count值為:
}<
/h3>
}<
/h3>
"sub"
>-1
<
/button>
"subn(3)"
>-n
<
/button>
"subasync"
>
-1 async<
/button>
"subnasync(4)"
>
-n async<
/button>
<
/div>
<
/template>
import
from
'vuex'
export
default},
methods:
,created()
, computed:
}<
/script>
"less" scoped>
<
/style>
Vuex核心概念Mutation Action
newvuex.store mutations commit increment mutations commit increment 10 mutations commit increment commit 當需要在物件上新增新屬性時,你應該 以新物件替換老物件。例如,利用 stage 3 的物件...
Vuex的核心概念入門必看
以下內容可直接用編輯器開啟檢視 doctype html en utf 8 viewport content width device width,initial scale 1.0 vuex的使用 title head 1.元件之間共享資料的方式 父元件向子元件傳值 v bind屬性繫結 子元件向...
vuex的五個核心概念簡述
vuex是vue.js應用設計的狀態管理架構,通俗理解,可以想象就是vue元件中的data 1.state 基本資料來源 簡單的state const store newvuex.store 2.mutatios 提交更改資料的方法 同步 儲存 第乙個引數是vuex中對應mutation的方法,第二...