vuex初學習
阿新 • • 發佈:2020-11-24
一、Vuex概述
1.是實現元件全域性狀態(資料)管理的一種機制,可以方便的實現元件之間的共享。
2.使用vuex統一管理狀態的好處
1.集中管理共享的資料,易於開發和維護
2.高效實現資料共享,提高開發效率
3.儲存在vuex中的資料都是響應式的,實時保持資料與頁面同步
3.適合儲存到vuex中的資料
一般情況下,共享資料存到vuex中。私有資料,存在自身的data即可。
二、Vuex的基本使用
1.安裝vuex
yarn add vuex
2.在src下新建一個store.js
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new Vuex.Store({ 提供唯一的公共資料來源,所有共享的資料都要統一放到Store中的State中進行儲存 state: { }, 用於變更資料 mutations: { }, 用於處理非同步任務 actions: { }, 包裝資料,加工成新的資料,類似vue的計算屬性 getters:{ } })
3.在main.js中匯入store例項並掛載到Vue例項上,之後就可以正常使用了
import Vue from 'vue'
import App from './App.vue'
// 匯入store例項物件
import store from './store'
Vue.config.productionTip = false
new Vue({
// 把store掛載到Vue例項上
store,
render: h => h(App),
}).$mount('#app')
三、核心概念
1.State
提供唯一的公共資料來源,所有共享的資料都要統一放到Store中的State中進行儲存
獲取方式:
1.this.$store.state.全域性資料名稱
2.import { mapState } from 'vuex' 通過匯入的mapState函式,將當前元件需要的資料,對映為當前元件的computed屬性
store.js
state: {
count: 0
},
元件中使用state中的資料
//html <h3>{{ $store.state.count }}</h3> //this 或 //html <h3>{{ count }}</h3> //js import { mapState } from 'vuex' computed: { ...mapState(['count']), },
2.Mutation
用於變更Store中的資料
在vuex中,只能通過mutation變更store中的資料
store.js
state: {
count: 0
},
mutations: {
// 實現指定步長自增
addN(state, step) {
state.count += step
},
// 實現指定步長自減
subN(state, step) {
state.count -= step
}
},
元件中使用
//html
<h3>{{ $store.state.count }}</h3>
<button @click="handle">+10</button>
//js
methods: {
handle() {
// 呼叫mutations裡的函式addN
this.$store.commit('addN', 10)
}
}
或
//html
<h3>{{ count }}</h3>
<button @click="handle">-10</button>
//js
import { mapState, mapMutations } from 'vuex'
computed: {
...mapState(['count']),
},
methods: {
...mapMutations(['subN']),
handle() {
this.subN(10)
}
}
3.Action
用於處理非同步任務
非同步變更資料,必須通過Action,而不能用Mutation,但是在Action中還是要通過觸發Mutation的方式間接變更資料
store.js
state: {
count: 0
},
mutations: {
// 實現指定步長自增
addN(state, step) {
state.count += step
},
// 實現指定步長自減
subN(state, step) {
state.count -= step
}
},
actions: {
addAsync(context, step) {
setTimeout(() => {
//在actions中,不能直接修改state中的資料
// 必須通過context.commit()觸發某個mutation才行
context.commit('addN', step)
}, 1000)
},
subAsync(context, step) {
setTimeout(() => {
context.commit('subN', step)
}, 1000)
}
},
元件中使用
//html
<h3>{{ $store.state.count }}</h3>
<button @click="handleAsync">+10 Async</button>
//js
methods: {
handleAsync() {
// dispatch專門用來觸發action
this.$store.dispatch('addAsync', 5)
}
}
或
//html
<h3>{{ count }}</h3>
<button @click="subAsync(5)">-5 Async</button>
//js
import { mapState, mapActions } from 'vuex'
computed: {
...mapState(['count'])
},
methods: {
...mapActions(['subAsync'])
}
4.Getter
1.包裝資料,加工成新的資料,類似vue的計算屬性
2.響應式,跟著Store實時變化
store.js
// 提供唯一的公共資料來源,所有共享的資料都要統一放到Store中的State中進行儲存
state: {
count: 0
},
getters:{
showNum(state){
return `我${state.count}歲了`
}
}
//html
<h3>{{ showNum }}</h3>
//js
import { mapState, mapGetters } from 'vuex'
computed: {
...mapState(['count']),
...mapGetters(['showNum'])
},