vuex工作流程
-
每個組件都共享Store中的數據, 以及每個組件都可以通過 $store.state 或者 getters 拿到傳入的數據,
-
通過事件 或者 回調函數 觸發 muation,進行同步更新數據, 從而觸發視圖更新
-
通過 提交 action 進行異步操作數據,
vuex實例
main.js
import Vue from 'vue'
import App from './App.vue'
import router from './router'
import store from './store/index'
Vue.config.productionTip = false
new Vue({
router,
store,
render: h => h(App)
}).$mount('#app')
src/store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
// 使用 了 Vue.use() 方法,官方文檔是這樣解釋的, 可以看到使用 use() 方法,必須提供一個 install 方法
// 該方法 有兩個 參數, 一個 是 Vue 的構造器, 另一個是可選項
Vue.use(Vuex)
export default new Vuex.Store({
state: {
num:0,
name:'我是測試數據',
mill: "我是getters用的"
},
getters:{
getMill(state) {
return state.mill
}
},
mutations: {
incr(state, payload){
state.num += payload
},
desr(state, payload){
state.num -= payload
}
},
actions: {
asyncIncr({commit}, payload){
setTimeout( () => {
commit('incr', payload)
}, 0)
}
},
modules: {
}
})
App.vue
<template>
<div id="app">
<h2>vuex</h2>
<p>{{$store.state.name}}</p>
<p>{{$store.getters.getMill}}</p>
{{$store.state.num}}
<button @click="addNum">點擊加1</button>
<button @click="AnsyncIncr">異步加一</button>
</div>
</template>
<script>
export default {
mounted() {
// setInterval(() => {
// this.$store.state.num += 1
// }, 1000)
},
methods:{
addNum(){
this.$store.commit('incr',1)
},
AnsyncIncr(){
this.$store.dispatch('asyncIncr', 2)
}
}
}
</script>
<style lang="less">
#app {
font-family: 'Avenir', Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
#nav {
padding: 30px;
a {
font-weight: bold;
color: #2c3e50;
&.router-link-exact-active {
color: #42b983;
}
}
}
</style>
分析
- 首先,組件都有一個$store屬性,通過new Vuex.store({}) 方法傳入的這個對象的數據
上面代碼使用了Vue.use方法,根據官方解釋,使用use方法,必須提供一個install方法,該方法 有兩個 參數, 一個 是 Vue 的構造器, 另一個是可選項
實現vuex
- 在store目錄下,新建myStore.js,在index.js文件中引入該文件
- 使用Vue.use必須提供一個install方法,第一個參數是Vue構造器,可以拿到vue一切屬性與方法
const install = _Vue => {
console.log("install")
}
export default {
install
}
- 在index.js文件中使用了new Vuex.Store()方法 所以還需要提供一個 Store的 class
let Vue
class Store {}
const install = _Vue => {
console.log("install")
Vue = _Vue // 用一個變量接收 _Vue 構造器
// 全局註冊一個混入,影響註冊之後所有創建的每個 Vue 實例
Vue.mixin({
beforeCreate() {
console.log(1)
}
})
}
export default {
install,
Store
}
結果如下:
由於數據是共享的,每個組件都需要拿到store數據,在使用時通過this.store屬性,可以通過$options拿到所有的屬性,結果如下:
let Vue
class Store {}
const install = _Vue => {
console.log("install")
Vue = _Vue // 用一個變量接收 _Vue 構造器
Vue.mixin({
beforeCreate() {
console.log(this.$options)
}
})
}
export default {
install,
Store
}
- 完善install方法
let Vue
class Store {}
const install = _Vue => {
console.log("install")
Vue = _Vue // 用一個變量接收 _Vue 構造器
Vue.mixin({
beforeCreate() {
//判斷 根 實例 有木有傳入store 數據源,
//如果傳入了, 就把它放到實例的 $store上
if (this.$options && this.$options.store) {
this.$store = this.$options.store
} else {
// 2. 子組件去取父級組件的$store屬性
this.$store = this.$parent && this.$parent.$store
}
}
})
}
export default {
install,
Store
}
- 通過new Vuex.Store() 方法,該方法傳入一個對象,包含state, getters, muations, action 等可選屬性
Store類必須接受一個參數,代碼如下:
let Vue
class Store {
constructor(options = {}) {
console.log(options)
}
}
const install = _Vue => {
console.log("install")
Vue = _Vue // 用一個變量接收 _Vue 構造器
Vue.mixin({
beforeCreate() {
//判斷 根 實例 有木有傳入store 數據源,
//如果傳入了, 就把它放到實例的 $store上
if (this.$options && this.$options.store) {
this.$store = this.$options.store
} else {
// 2. 子組件去取父級組件的$store屬性
this.$store = this.$parent && this.$parent.$store
}
}
})
}
export default {
install,
Store
}
結果如下:
- 完成state源碼
class Store {
constructor(options = {}) {
this.state = options.state
}
}
App.vue
<template>
<div id="app">
<h2>vuex</h2>
<p>{{$store.state.name}}</p>
</div>
</template>
<script>
export default {}
</script>
- 手寫getters
原生實例:
import Vue from "vue"
import Vuex from "vuex"
Vue.use(Vuex)
export default new Vuex.Store({
state: {
name: "我是原生的state數據",
mill: "我是getters用的"
},
getters: {
getMill(state) {
return state.mill
}
},
mutations: {},
actions: {},
modules: {}
})
App.vue
<template>
<div id="app">
<h2>vuex</h2>
<p>{{mill}}</p>
</div>
</template>
<script>
export default {
computed: {
mill() {
return this.$store.getters.getMill
}
}
}
</script>
- 打印 this.$store.getters, 可以發現是一個對象
- 需要將getters的方法作爲對象的屬性返回,並且傳入一個state參數
- 實現getters
class Store {
constructor(options = {}) {
this.state = options.state
// 定義實例上的 getters
this.getters = {}
// 遍歷所有的對象中的方法名
Object.keys(options.getters).forEach(key => {
// 重新構造 this.getters 對象
Object.defineProperty(this.getters, key, {
get: () => {
return options.getters[key](this.state)
}
})
})
}
}
現在基本上實現了state,getters,但是會有一個問題,直接改 vuex 的數據是可以變化的,但是現在無法改變
錯誤演示:
App.vue
<template>
<div id="app">
<h2>vuex</h2>
<p>{{mill}}</p>
<p>{{$store.state.num}}</p>
</div>
</template>
<script>
export default {
computed: {
mill() {
console.log(this.$store.getters)
return this.$store.getters.getMill
}
},
mounted() {
setInterval(() => {
this.$store.state.num += 1
}, 1000)
}
}
</script>
index.js
import Vue from "vue"
import Vuex from "./myStore"
Vue.use(Vuex)
export default new Vuex.Store({
state: {
name: "我是原生的state數據",
mill: "我是getters用的",
num: 1
},
getters: {
getMill(state) {
return state.mill
}
},
mutations: {},
actions: {},
modules: {}
})
然而使用 我們自己寫的 發現確不變化, 那麼需要來解決這個問題
我們知道 ,vue 中的數據只要是寫在 data 中的,都是支持 響應式的, 所以 我們只有把 vuex 中的state 定義在 Vue中的 data中
改寫代碼:
class Store {
constructor(options = {}) {
this.state = new Vue({
data() {
return {
state: options.state
}
}
})
// 定義實例上的 getters
this.getters = {}
// 遍歷所有的對象中的方法名
Object.keys(options.getters).forEach(key => {
// 重新構造 this.getters 對象
Object.defineProperty(this.getters, key, {
get: () => {
return options.getters[key](this.state)
}
})
})
}
}
但如果這樣寫的 話, 就不能像原先那樣調用了,需要多調一層 state才能拿到數據, (使用類的屬性訪問器setter, getter)解決這個問題,參考 es6文檔
改寫代碼如下:
class Store {
constructor(options = {}) {
this.myState = new Vue({
data() {
return {
state: options.state
}
}
})
// 定義實例上的 getters
this.getters = {}
// 遍歷所有的對象中的方法名
Object.keys(options.getters).forEach(key => {
// 重新構造 this.getters 對象
Object.defineProperty(this.getters, key, {
get: () => {
return options.getters[key](this.state)
}
})
})
}
get state() {
return this.myState.state
}
}
到這裏,已經基本實現了, 數據響應式變化, state, getters 了
整體代碼:
let Vue
class Store {
constructor(options = {}) {
// 核心代碼: 保證數據都是響應式的
this.myState = new Vue({
data() {
return {
state: options.state
}
}
})
// 定義實例上的 getters
this.getters = {}
// 遍歷所有的對象中的方法名
Object.keys(options.getters).forEach(key => {
// 重新構造 this.getters 對象
Object.defineProperty(this.getters, key, {
get: () => {
return options.getters[key](this.state)
}
})
})
}
get state() {
return this.myState.state
}
}
const install = _Vue => {
console.log("install")
Vue = _Vue // 用一個變量接收 _Vue 構造器
Vue.mixin({
beforeCreate() {
//判斷 根 實例 有木有傳入store 數據源,
//如果傳入了, 就把它放到實例的 $store上
if (this.$options && this.$options.store) {
this.$store = this.$options.store
} else {
// 2. 子組件去取父級組件的$store屬性
this.$store = this.$parent && this.$parent.$store
}
}
})
}
export default {
install,
Store
}
- 實現commit 方法 , 進行修改數據數據,先看原生的
$store 下 有個 commit 方法, commit() 方法 提供兩個參數, 一個 muation裏定義的函數名 , 一個是傳入的後續參數
let mutations = {} // 定義一個對象收集所有傳入的 mutations
Object.keys(options.mutations).forEach(key => {
mutations[key] = () => {
}
})
- commit方法實現
// 提供commit 方法
this.commit = (key, payload) => {
mutations[key](payload)
}
- 所以上邊 mutations 的訂閱 ,它收集的是所有方法, 需要遍歷所有的key , 所以取出所有的key 進行 一次執行
// 定義 muations
let mutations = {}
Object.keys(options.mutations).forEach(key => {
mutations[key] = payload => {
options.mutations[key](this.state, payload)
}
})
- 整理代碼如下:
let Vue
class Store {
constructor(options = {}) {
// 核心代碼: 保證數據都是響應式的
this.myState = new Vue({
data() {
return {
state: options.state
}
}
})
// 定義實例上的 getters
this.getters = {}
// 遍歷所有的對象中的方法名
Object.keys(options.getters).forEach(key => {
// 重新構造 this.getters 對象
Object.defineProperty(this.getters, key, {
get: () => {
return options.getters[key](this.state)
}
})
})
// 定義 muations
let mutations = {}
Object.keys(options.mutations).forEach(key => {
mutations[key] = payload => {
options.mutations[key](this.state, payload)
}
})
// 提供commit 方法
this.commit = (key, payload) => {
mutations[key](payload)
}
}
get state() {
return this.myState.state
}
}
const install = _Vue => {
console.log("install")
Vue = _Vue // 用一個變量接收 _Vue 構造器
Vue.mixin({
beforeCreate() {
//判斷 根 實例 有木有傳入store 數據源,
//如果傳入了, 就把它放到實例的 $store上
if (this.$options && this.$options.store) {
this.$store = this.$options.store
} else {
// 2. 子組件去取父級組件的$store屬性
this.$store = this.$parent && this.$parent.$store
}
}
})
}
export default {
install,
Store
}
- 實現dispatch 方法 ,就跟 commit 差不多 了
// 收集 actions
let actions = {}
Object.keys(options.actions).forEach(key => {
actions[key] = payload => {
options.actions[key](this, payload)
}
})
this.dispatch = (key, payload) => {
actions[key](payload)
}
- 整理代碼如下:
let Vue
class Store {
constructor(options = {}) {
// 核心代碼: 保證數據都是響應式的
this.myState = new Vue({
data() {
return {
state: options.state
}
}
})
// 定義實例上的 getters
this.getters = {}
// 遍歷所有的對象中的方法名
Object.keys(options.getters).forEach(key => {
// 重新構造 this.getters 對象
Object.defineProperty(this.getters, key, {
get: () => {
return options.getters[key](this.state)
}
})
})
// 定義 muations
let mutations = {}
Object.keys(options.mutations).forEach(key => {
mutations[key] = payload => {
options.mutations[key](this.state, payload)
}
})
// 提供commit 方法
this.commit = (key, payload) => {
mutations[key](payload)
}
// 收集 actions
let actions = {}
Object.keys(options.actions).forEach(key => {
actions[key] = payload => {
options.actions[key](this, payload)
}
})
this.dispatch = (key, payload) => {
actions[key](payload)
}
}
get state() {
return this.myState.state
}
}
const install = _Vue => {
console.log("install")
Vue = _Vue // 用一個變量接收 _Vue 構造器
Vue.mixin({
beforeCreate() {
//判斷 根 實例 有木有傳入store 數據源,
//如果傳入了, 就把它放到實例的 $store上
if (this.$options && this.$options.store) {
this.$store = this.$options.store
} else {
// 2. 子組件去取父級組件的$store屬性
this.$store = this.$parent && this.$parent.$store
}
}
})
}
export default {
install,
Store
}
參考:https://blog.csdn.net/qq_36407748/article/details/102778062