【问题标题】:VuesJS components templateVue JS 组件模板
【发布时间】:2019-09-12 07:28:18
【问题描述】:

我是 VueJS 初学者,我正在努力理解一些组件逻辑。

如果我有我的组件(为清楚起见进行了简化):

Vue.component('nav-bar', {
        template: '<nav [some code] ></nav>'
}

这个组件代表了我页面的整个导航栏。 在我的 HTML 文件中,如何在组件中插入代码?

类似:

<nav-bar>
    <button></button>
    ...
</nav-bar>

你能告诉我这样做是否正确吗?

【问题讨论】:

标签: vue.js components


【解决方案1】:

我能想到的至少有三个选项:


1。以ref 为例

Vue.component('NavBar', {
  template: `
    <nav>
      <slot></slot>
    </nav>
  `,

  methods: {
    run() {
      console.log('Parent\'s method invoked.');
    }
  }
});

new Vue().$mount('#app');
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>

<div id="app">
  <nav-bar ref="navbar">
    <button @click="$refs.navbar.run()">Run with refs</button>
  </nav-bar>
</div>

2。使用范围&lt;slot&gt;

Vue.component('NavBar', {
  template: `
    <nav>
      <slot v-bind="$options.methods"></slot>
    </nav>
  `,

  methods: {
    run() {
      console.log('Parent\'s method invoked.');
    }
  }
});

new Vue().$mount('#app');
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>

<div id="app">
  <nav-bar>
    <template #default="methods">
      <button @click="methods.run">Run with slot props</button>
    </template>
  </nav-bar>
</div>

3。使用provide 和inject

Vue.component('NavBar', {
  template: `
    <nav>
      <slot></slot>
    </nav>
  `,
  
  provide() {
    const props = {
      ...this.$options.methods,

      // The rest of props you'd like passed down to the child components.
    };

    return props;
  },

  methods: {
    run() {
      console.log('Parent\'s method invoked.');
    }
  }
});

// In order to "receive" or `inject` the parent props,
// the child(ren) needs to be a component itself.
Vue.component('Child', {
  template: `
    <button @click="run">
      <slot></slot>
    </button>
  `,

  // Inject anything `provided` by the direct parent
  // This could also be `data` or `props`, etc.
  inject: ['run']
});

new Vue().$mount('#app');
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.min.js"></script>

<div id="app">
  <nav-bar>
    <template>
      <child>Run with injected method</child>
    </template>
  </nav-bar>
</div>

【讨论】:

    猜你喜欢
    • 2018-07-01
    • 2020-10-08
    • 2021-10-20
    • 2018-04-17
    • 2018-03-08
    • 1970-01-01
    • 2016-02-05
    • 2019-11-12
    • 2018-07-07
    相关资源
    最近更新 更多