几分钟让你找到工作,2023年前端面试题总结之vuex原理

2023-01-31 0 250

路子及业务流程

具体来说采用vue.use(vuex)说明vuex是vue的应用程序,根本无法被vue采用——示例化Store并传至对用——Store转化成到根模块上。以内四个关键步骤便能采用vuex同时实现统计数据在模块中的共享资源了。

表述vuex文档,撰写install方式

当采用到vue.use的这时候

“`

const install = (_vue) => {

if(vue!=_vue){

vue=_vue;

}

vue.mixin({

beforeCreate(){

if(this.$options && this.$options.Store){

this.$store = this.$options.Store;

}else{

this.$store = this.$parent && this.$parent.$store;

}

}

})

}

“`

表述vuex文档,撰写Store类

当Store类被示例化时,会执行constructor构造器并且传至option所需的参数,在对state、getters、mutations、actions撰写。

1、同时实现state:理论上讲,直接把参数中的state赋值当前模块上即可,这样会引发一个问题,state的值无法动态改变。要采用state双向绑定能直接采用vue示例中data方式,然后在通过get进行属性的截取。

“`

this.getState = new vue({

data:function(){

return{

state:option.state

}

}

})

“`

2、同时实现getters:通过Ojbect.defi

“`

this.getters={};

for(let key in option.getters){

Object.defineProperty(this.getters,key,{

get(){

return option.getters[key](_that.state);

}

})

}

“`

3、同时实现mutations:把参数mutations里面的方式重新用一个变量去接收,作用是防止变量的全局污染。表述commit函数,当被执行时,触发表述mutaion对象里面的方式。

“`

let mutations = {};

for(let key in option.mutations){

mutations[key]=value=>{

option.mutations[key](this.state,value);

}

}

this.commit = (key,value=null) => mutations[key](value);

“`

4、同时实现actions:方式同上,有个地方需要作出微调,传递的参数是当前的执行期上下文。

“`

let actions = {};

for(let key in option.actions){

actions[key]=()=>{

option.actions[key](this);

}

}

this.dispatch = key => actions[key]();

“`

[项目案例](

https://github.com/zhuyangmsg/vuex)

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务