Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

vue1.0源码解析六:实现常用的指令 #9

Open
lihongxun945 opened this issue Jul 15, 2018 · 0 comments
Open

vue1.0源码解析六:实现常用的指令 #9

lihongxun945 opened this issue Jul 15, 2018 · 0 comments

Comments

@lihongxun945
Copy link
Owner

在上一篇结束的时候,我们已经完成了 tiny-vue 的基本架构,接下来,只要实现一些内置的指令,我们的代码就比较完善了。当然请别千万别在生产环境中使用哦,我们造轮子是为了学习,而不是为了真的用。

我们来实现一个 v-text 指令,其实非常简单,只要在 update 的时候把获取的值写到 innerHTML 中就行了。

export default {
  bind () {
  },
  update (value) {
    const el = this.descriptor.el
    el.innerHTML = value
  }
}

是不是很简单。

再实现一个 v-model 指令,这就是我们所说的双向绑定。那么既然是双向显然要分两步实现:

1, 当 DOM input 事件的时候,通过 watcher 把新的值写入 vm
2, 当vm update 时,把新的值写入 DOM

export default {
  bind () {
    const el = this.descriptor.el
    el.addEventListener('input', () => {
      this._watcher.set(el.value)
    })
  },
  update (value) {
    const el = this.descriptor.el
    el.value = value
  }
}

是不是也很简单。

还有常见的 v-ifv-bind 等指令都很容易实现,大家可以自行尝试一下。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant