十年网站开发经验 + 多家企业客户 + 靠谱的建站团队
量身定制 + 运营维护+专业推广+无忧售后,网站问题一站解决
这期内容当中小编将会给大家带来有关怎么在Vue 3.0中实现双向绑定,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

创新互联是一家专注于网站制作、网站建设与策划设计,囊谦网站建设哪家好?创新互联做网站,专注于网站建设10多年,网设计领域的专业建站公司;建站业务涵盖:囊谦等地区。囊谦做网站价格咨询:13518219792
1、定义构造函数
function Vue(option){
this.$el = document.querySelector(option.el); //获取挂载节点
this.$data = option.data;
this.$methods = option.methods;
this.deps = {}; //所有订阅者集合 目标格式(一对多的关系):{msg: [订阅者1, 订阅者2, 订阅者3], info: [订阅者1, 订阅者2]}
this.observer(this.$data); //调用观察者
this.compile(this.$el); //调用指令解析器
}2、定义指令解析器
Vue.prototype.compile = function (el) {
let nodes = el.children; //获取挂载节点的子节点
for (var i = 0; i < nodes.length; i++) {
var node = nodes[i];
if (node.children.length) {
this.compile(node) //递归获取子节点
}
if (node.hasAttribute('l-model')) { //当子节点存在l-model指令
let attrVal = node.getAttribute('l-model'); //获取属性值
node.addEventListener('input', (() => {
this.deps[attrVal].push(new Watcher(node, "value", this, attrVal)); //添加一个订阅者
let thisNode = node;
return () => {
this.$data[attrVal] = thisNode.value //更新数据层的数据
}
})())
}
if (node.hasAttribute('l-html')) {
let attrVal = node.getAttribute('l-html'); //获取属性值
this.deps[attrVal].push(new Watcher(node, "innerHTML", this, attrVal)); //添加一个订阅者
}
if (node.innerHTML.match(/{{([^\{|\}]+)}}/)) {
let attrVal = node.innerHTML.replace(/[{{|}}]/g, ''); //获取插值表达式内容
this.deps[attrVal].push(new Watcher(node, "innerHTML", this, attrVal)); //添加一个订阅者
}
if (node.hasAttribute('l-on:click')) {
let attrVal = node.getAttribute('l-on:click'); //获取事件触发的方法名
node.addEventListener('click', this.$methods[attrVal].bind(this.$data)); //将this指向this.$data
}
}
}3、定义观察者(区别在这一块代码)
Liu.prototype.observer = function (data) {
const that = this;
for(var key in data){
that.deps[key] = []; //初始化所有订阅者对象{msg: [订阅者], info: []}
}
let handler = {
get(target, property) {
return target[property];
},
set(target, key, value) {
let res = Reflect.set(target, key, value);
var watchers = that.deps[key];
watchers.map(item => {
item.update();
});
return res;
}
}
this.$data = new Proxy(data, handler);
}4、定义订阅者
function Watcher(el, attr, vm, attrVal) {
this.el = el;
this.attr = attr;
this.vm = vm;
this.val = attrVal;
this.update(); //更新视图
}5、更新视图
Watcher.prototype.update = function () {
this.el[this.attr] = this.vm.$data[this.val]
}以上代码定义在一个Vue.js文件中,在需要使用双向绑定的地方引入即可。
尝试使用一下:
Document {{msg}}
上述就是小编为大家分享的怎么在Vue 3.0中实现双向绑定了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注创新互联行业资讯频道。