mini-vue实现之双向绑定

180 阅读1分钟

mini-vue代码已放到github上。

之前已经实现了响应式原理,但是在输入框输入的时候,数据并没有改变。

<input type='text' v-model='msg' />

其实双向绑定的实现很简单,我们只需要在解析指令的时候,为input框绑定input事件,将node的值更新到data中。

modelUpdater(node, value, key) {
    node.value = value;
    new Watcher(this.vm, key, (newValue) => {
        node.value = newValue;
    });
    //  双向绑定
    node.addEventListener('input', () => {
        this.vm[key] = node.value;
    });
}