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

如何构建自己的抽象组件? #119

Open
wuxianqiang opened this issue Apr 1, 2019 · 0 comments
Open

如何构建自己的抽象组件? #119

wuxianqiang opened this issue Apr 1, 2019 · 0 comments

Comments

@wuxianqiang
Copy link
Owner

指令的职责是,当表达式的值改变时,将其产生的连带影响,响应式地作用于 DOM。事实上,指令相当不灵活,不能做一些复杂的操作。例如,指令不能触发事件。那么怎么解决这一问题呢?答案是使用抽象组件!

抽象组件与普通组件类似,只是它们不向DOM呈现任何内容。他们只是添加额外的行为。

<div id="app" class="container">
  <foo>
    <p>hello</p>
  </foo>
</div>

抽象组件foo并不能显示任何DOM元素,只是添加一些额外的功能。

<div id="app" class="container">
  <p>hello</p>
</div>

vue内置的抽象组件有<transition><component><slot>等等。

export default {
  // 在 Vue 中启用抽象组件
  abstract: true,
  // 我们不需要任何包裹的元素,只需要返回里面的内容即可
  render() {
    try {
      return this.$slots.default[0];
    } catch (e) {
      throw new Error('没有内容');
    }
    return null;
  },
  methods: {
    // 在这里使用$emit派发事件...
  }
}

更多抽象组件用法可以参考这里:传送门

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

No branches or pull requests

1 participant