GIF 2021-4-23 22-46-17.gif
開(kāi)始
MyVuex.js源碼恳蹲,這里為了避免和已經(jīng)導(dǎo)入Vuex的項(xiàng)目沖突,所以名字有區(qū)別
let instance = null
class Mvx {
store = {
state: null
}
constructor(Vue) {
const that = this
this.store.state = new Vue({
data() {
return {
name: 12
}
}
})
this.store.commit = {
SET_NAME(value) {
that.store.state.name = that.store.state.name + value
},
ASYNC_SET_NAME(value) {
return new Promise(resolve => {
setTimeout(() => {
that.store.state.name = that.store.state.name + value
resolve(that.store.state.name)
}, 1000)
})
}
}
/* 或者用Vue.prototype.$mstore = store俩滥,混入的形式是掛在實(shí)例上嘉蕾,prototype是在原型上,混入的化感覺(jué)性能更好 */
Vue.mixin({
beforeCreate() {
this.$mstore = that.store
}
})
}
}
export const mapStates = (status) => {
let state = {}
status.forEach(s => {
state[s] = () => instance.store.state[s]
})
return state
}
export const mapActions = (actions) => {
let action = {}
actions.forEach(a => {
action[a] = instance.store.commit[a]
})
return action
}
export default {
install(Vue) {
instance = new Mvx(Vue)
return instance
}
}
如何使用霜旧?
在main.js內(nèi)導(dǎo)入我的Vuex
import Mvx from './MyVuex'
Vue.use(Mvx)
template模板中错忱,測(cè)試從實(shí)例直接使用和map state和action之后使用
<template>
<section class="">
<p class="fsize fcorg pt10 pb10">
<span class="fcgreen">$mstore.state.name : </span>{{$mstore.state.name}}
</p>
<p class="fsize fcorg pt10 pb10">
<span class="fcgreen">map name : </span>{{name}}
</p>
<el-button @click="changeName" size="small" type="success">change name</el-button>
<el-button @click="SET_NAME(100)" size="small" type="primary">change name By mapActions</el-button>
<el-button @click="ASYNC_SET_NAME(10)" size="small" type="warning">By AsyncMapAction</el-button>
</section>
</template>
在模板中使用
// 導(dǎo)入
import { mapStates, mapActions } from '../MyVuex'
export default {
name: '/test-my-vuex',
data() {
return {}
},
computed: {
/* 通過(guò)計(jì)算屬性,map到data */
...mapStates(['name'])
},
methods: {
/* 通過(guò)mapActions颁糟,map到methods中航背。測(cè)試:1.直接調(diào)用喉悴,2.異步調(diào)用棱貌,3.直接通過(guò)實(shí)例調(diào)用 */
...mapActions(['SET_NAME', 'ASYNC_SET_NAME']),
changeName() {
this.$mstore.commit.SET_NAME(12)
}
}
}
推介一下自己的基于Vue2.6的蘭陵王框架https://lanling.diumx.com 和 基于Vue3+Ts+Vite的花木蘭框架http://mulan.diumx.com