当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 基于JavaScript实现一个简单的Vue

基于JavaScript实现一个简单的Vue

2019年06月03日  | 移动技术网IT编程  | 我要评论

object.defineproperty()

实现之前我们得先看一下object.defineproperty的实现,因为vue主要是通过数据劫持来实现的,通过get、set来完成数据的读取和更新。

var obj = {name:'wclimb'}
var age = 24
object.defineproperty(obj,'age',{
enumerable: true, // 可枚举
configurable: false, // 不能再define
get () {
return age
},
set (newval) {
console.log('我改变了',age +' -> '+newval);
age = newval
}
})
> obj.age
> 24
> obj.age = 25;
> 我改变了 24 -> 25
> 25

从上面可以看到通过get获取数据,通过set监听到数据变化执行相应操作,还是不明白的话可以去看看object.defineproperty文档。

流程图

 

html代码结构

<div id="wrap"> 
 <p v-html="test"></p>
 <input type="text" v-model="form">
 <input type="text" v-model="form">
 <button @click="changevalue">改变值</button>
 {{form}}
</div>

vue结构

class vue{
constructor(){}
proxydata(){}
observer(){}
compile(){}
compiletext(){}
}
class watcher{
constructor(){}
update(){}
}

vue constructor 构造函数主要是数据的初始化

proxydata 数据代理

observer 劫持监听所有数据

compile 解析dom

compiletext 解析dom里处理纯双花括号的操作

watcher 更新视图操作

vue constructor 初始化

class vue{
constructor(options = {}){
this.$el = document.queryselector(options.el);
let data = this.data = options.data;
// 代理data,使其能直接this.xxx的方式访问data,正常的话需要this.data.xxx
object.keys(data).foreach((key)=> {
this.proxydata(key);
});
this.methods = obj.methods // 事件方法
this.watchertask = {}; // 需要监听的任务列表
this.observer(data); // 初始化劫持监听所有数据
this.compile(this.$el); // 解析dom
}
}

上面主要是初始化操作,针对传过来的数据进行处理

proxydata 代理data

class vue{
constructor(options = {}){
......
}
proxydata(key){
let that = this;
object.defineproperty(that, key, {
configurable: false,
enumerable: true,
get () {
return that.data[key];
},
set (newval) {
that.data[key] = newval;
}
});
}
}

上面主要是代理data到最上层,this.xxx的方式直接访问data

observer 劫持监听

class vue{
constructor(options = {}){
......
}
proxydata(key){
......
}
observer(data){
let that = this
object.keys(data).foreach(key=>{
let value = data[key]
this.watchertask[key] = []
object.defineproperty(data,key,{
configurable: false,
enumerable: true,
get(){
return value
},
set(newvalue){
if(newvalue !== value){
value = newvalue
that.watchertask[key].foreach(task => {
task.update()
})
}
}
})
})
}
}

同样是使用object.defineproperty来监听数据,初始化需要订阅的数据。

把需要订阅的数据到push到watchertask里,等到时候需要更新的时候就可以批量更新数据了。??下面就是;

遍历订阅池,批量更新视图。

set(newvalue){
if(newvalue !== value){
value = newvalue
// 批量更新视图
that.watchertask[key].foreach(task => {
task.update()
})
}
}

compile 解析dom

class vue{
constructor(options = {}){
......
}
proxydata(key){
......
}
observer(data){
......
}
compile(el){
var nodes = el.childnodes;
for (let i = 0; i < nodes.length; i++) {
const node = nodes[i];
if(node.nodetype === 3){
var text = node.textcontent.trim();
if (!text) continue;
this.compiletext(node,'textcontent')
}else if(node.nodetype === 1){
if(node.childnodes.length > 0){
this.compile(node)
}
if(node.hasattribute('v-model') && (node.tagname === 'input' || node.tagname === 'textarea')){
node.addeventlistener('input',(()=>{
let attrval = node.getattribute('v-model')
this.watchertask[attrval].push(new watcher(node,this,attrval,'value'))
node.removeattribute('v-model')
return () => {
this.data[attrval] = node.value
}
})())
}
if(node.hasattribute('v-html')){
let attrval = node.getattribute('v-html');
this.watchertask[attrval].push(new watcher(node,this,attrval,'innerhtml'))
node.removeattribute('v-html')
}
this.compiletext(node,'innerhtml')
if(node.hasattribute('@click')){
let attrval = node.getattribute('@click')
node.removeattribute('@click')
node.addeventlistener('click',e => {
this.methods[attrval] && this.methods[attrval].bind(this)()
})
}
}
}
},
compiletext(node,type){
let reg = /{{(.*)}}/g, txt = node.textcontent;
if(reg.test(txt)){
node.textcontent = txt.replace(reg,(matched,value)=>{
let tpl = this.watchertask[value] || []
tpl.push(new watcher(node,this,value,type))
return value.split('.').reduce((val, key) => {
return this.data[key];
}, this.$el);
})
}
}
}

这里代码比较多,我们拆分看你就会觉得很简单了

首先我们先遍历el元素下面的所有子节点,node.nodetype === 3 的意思是当前元素是文本节点,node.nodetype === 1 的意思是当前元素是元素节点。因为可能有的是纯文本的形式,如纯双花括号就是纯文本的文本节点,然后通过判断元素节点是否还存在子节点,如果有的话就递归调用compile方法。下面重头戏来了,我们拆开看:

if(node.hasattribute('v-html')){
let attrval = node.getattribute('v-html');
this.watchertask[attrval].push(new watcher(node,this,attrval,'innerhtml'))
node.removeattribute('v-html')
}

上面这个首先判断node节点上是否有v-html这种指令,如果存在的话,我们就发布订阅,怎么发布订阅呢?只需要把当前需要订阅的数据push到watchertask里面,然后到时候在设置值的时候就可以批量更新了,实现双向数据绑定,也就是下面的操作

that.watchertask[key].foreach(task => {
task.update()
})

然后push的值是一个watcher的实例,首先他new的时候会先执行一次,执行的操作就是去把纯双花括号 -> 1,也就是说把我们写好的模板数据更新到模板视图上。

最后把当前元素属性剔除出去,我们用vue的时候也是看不到这种指令的,不剔除也不影响

至于watcher是什么,看下面就知道了

watcher

that.watchertask[key].foreach(task => {
task.update()
})

之前发布订阅之后走了这里面的操作,意思就是把当前元素如:node.innerhtml = '这是data里面的值'、node.value = '这个是表单的数据'

那么我们为什么不直接去更新呢,还需要update做什么,不是多此一举吗?

其实update记得吗?我们在订阅池里面需要批量更新,就是通过调用watcher原型上的update方法。

总结

以上所述是小编给大家介绍的基于javascript实现一个简单的vue,希望对大家有所帮助

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网