原理
場景:打算開發中大型應用 特點: 集中式數據管理, 一處修改,多處使用 思維: store this.$store.commit('increment') -> mutations this.$store.dispatch('jia') -> actions mapActions() ->actions mapGetters()->getters 學生 代課老師 校長 財務 版主任 學生 components - > actions -> mutations -> state <- getters <- components 發送請求 處理 修改狀態 業務邏輯 修改state 讀取state 異步 state<-$store.state <- 學生
安裝 安裝包 npm i vuex -s
引入 import vuex from 'vuex
安裝插件 Vue.use(vuex)
注冊到根 new Vue({store})
①store.js 引入vue和vuex 實例store對象 let store =new ②main.js注冊到根 ③在store.js引入actions,mutations,getter,state,寫在實例內作為對象 ④各個模塊單獨的js文件內部暴露export
案例,點擊讓數字從0++
把 mapActions,mapGetters 引入把想action請求的方式寫在methods內,然后去往actions
<template>
<div id="app">
<h3>vuex</h3>
<input type="button" value="按鈕" @click="jia">
<hr>
<!-- {{count}} -->
<!-- {{this.$store.state.count}} -->
</div>
</template>
<script>
import vuex from 'vuex'
// console.log(vuex) //vuex={store,mapActions,mapGetters}
// 解構賦值
// import varname from {}
// let varname={}
// let {a,b}={a:1,b:2}
// a→1
// b→2
import {mapActions,mapGetters} from 'vuex'
export default {
data() {
return {
count:0
}
},
methods: {
jia(){
// console.log(this.$store)
// console.log(mapActions,mapGetters)
// this.$store.dispatch(請求類型,負載,配置)
this.$store.dispatch('jia',1)
}
},
}
</script>
最后完成,如果想直接從state拿數據就在app.vue的
{{this.$store.state.count}}
2、上面是comonent直接從state拿的數據,沒有通過getters,下面通過getters拿數據
3、在2里面雖然通過getters拿數據,但是沒有用mapActions
在template模板中是
<input type="button" value="按鈕" @click="jia(1)">
methods: mapActions(['jia']),
引用types后