手写 vuex
插件固定写法
let Vue = null
const install=(v)=>{
Vue = v
}
export default{
install
}
混入
const install=(v)=>{
Vue = v
Vue.mixin({// 混入 以后子组件都可以使用$store 访问
beforeCreate() {
//判断是否为根节点,根节点会挂载store
if(this.$options && this.$options.store){
this.$store = this.$options.store
}else{
this.$store = this.$parent && this.$parent.$store
}
},
})
}
创建 Store
由于需要使用 new Vuex.Store 来创建,所以 Vuex 中要包含Store
class Store{
constructor(options){
}
}
如何实现响应式
可以借助vue 响应式来实现 创建一个vue 实例,将store 放在data 方法中
class Store{
constructor(options){
this.vm = new Vue({
data:{
state:options.state
}
})
}
get state(){
return this.vm.state
}
}
实现getter
let getters = options.getters || {}
this.getters = {}
Object.keys(getters).forEach(getName=>{
Object.defineProperty(this.getters,getName,{
get:()=>{return getters[getName](this.state)}
})
})
实现mutations commit
let mutations = options.mutations || {}
this.mutations = {}
Object.keys(mutations).forEach(mutationName=>{
this.mutations[mutationName] = payload=>{
mutations[mutationName](this.state,payload)
}
})
commit = (method, payload) => {
this.mutations[method](payload)
}
实现 actions dispatch
let actions = options.actions || {}
this.actions = {}
Object.keys(actions).forEach(actionName => {
this.actions[actionName] = payload => {
actions[actionName](this, payload)
}
})
dispatch = (method, payload)=>{
this.actions[method](payload)
}
完整代码
let Vue = null
class Store {
constructor(options) {
this.vm = new Vue({
data(){
return {
state: options.state
}
}
})
let getters = options.getters || {}
this.getters = {}
Object.keys(getters).forEach(getName => {
Object.defineProperty(this.getters, getName, {
get: () => { return getters[getName](this.state) }
})
})
let mutations = options.mutations || {}
this.mutations = {}
Object.keys(mutations).forEach(mutationName => {
this.mutations[mutationName] = payload => {
mutations[mutationName](this.state, payload)
}
})
let actions = options.actions || {}
this.actions = {}
Object.keys(actions).forEach(actionName => {
this.actions[actionName] = payload => {
actions[actionName](this, payload)
}
})
}
commit = (method, payload) => {
this.mutations[method](payload)
}
dispatch = (method, payload)=>{
this.actions[method](payload)
}
get state() {
return this.vm.state
}
}
const install = (v) => {
Vue = v
Vue.mixin({// 混入 以后子组件都可以使用$store 访问
beforeCreate() {
//判断是否为根节点,根节点会挂载store
if (this.$options && this.$options.store) {
this.$store = this.$options.store
} else {
this.$store = this.$parent && this.$parent.$store
}
},
})
}
export default {
install,
Store
}
简单来讲就是将const store = new Vuex.Store({
.....
})内部传递的参数在 Vuex 中实现一下