Vuex

1 , 安裝
(1):直接下載
https://unpkg.com/[email protected]
(2):npm
2 , Vuex的創建
npm install vuex --save ;
<!--數據-->
let store = new Vuex.Store({ state:{
} ,
getters:{
<!--數據處理-->
} ,
mutations:{
<!--方法,不支持異步-->
} ,
actions:{
<!--方法,支持異步-->
} ,
modules:{
<!--模塊-->
}
}) ;
<!--導出-->
export default store ;
3 , Vuex的結構樹
store
index.js<!-- 用來組裝模塊和導出store -->
state.js<!-- 用來存放數據 -->
getters.js <!-- 用來計算數據 ,
外部調用方法 this.$store.getters.fn -->
mutations.js <!-- 同來存放方法 ,
外部調用方法 this.$store.commit(fn)
但不支持異步操作 ;
-->
actions.js <!-- 和mutations差不多
外部調用方法 this.$store.dispatch(fn)
支持異步操作
-->
modules
m1 <!-- 模塊1 -->
m2 <!-- 模塊2 -->
4 , 結構樹的實例
(1):state的實例
//存放數據
const state = {
name:'123' ,
age:24 ,
} ;
(2):getters的實例
export default state ;
const getters = {
} ,
getName(state){
return state.name ;
getAge(state){
return state.age ;
} } ;
export default getters ;
(3):mutations的實例
} ,
//各種方法
export default {
setName(state,val){
state.name = val ;
export default {
setAge(state,val){
state.age = val ;
} }
setAge(state){
(4):actions的實例
export defaulte {
state.commit('setAge',1000) ;
} }
----------------------------------------
setAge({ commit }){
store ,
commit('setAge',1000)
} }
import store from './store/index.js'
5 , 掛載到main.js中 let app = new Vue({
<!--
el:'#app', })
6 , 關於mapState,mapGetters、mapActions、mapMutations
由於每次調用vuex中的數據或者方法都要使用$store.state.數據
比較麻煩,因此使用mapState等
-->
在vue組件中引入mapState
import {mapState,mapGetters,mapActions,mapMutations} from 'vuex' ;
在vue組件中的computed或者methods中使用...mapState
computed:{
<!--
這樣子就可以直接用name和age來代替
$store.state.name和$store.state.age
-->
...mapState([
'name',
])
'age' ,
} , methods:{
<!--
點擊的時候可以直接使用fn(val)
button @click='fn(val)' ;
fn就是this.$store.commit('setName') ;
-->
...mapMutations({
fn:'setName' ,
})
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章