【问题标题】:How to use same template on different components in vue js?如何在 vue js 中的不同组件上使用相同的模板?
【发布时间】:2018-05-16 06:04:23
【问题描述】:

目前我正在使用 as

<template> ... </template>
<script src="test1.js"> </script>

我所有的业务逻辑都是用 test1.js 编写的。现在我需要使用具有相同模板的 test2.js。我需要用不同的组件重用模板。

我当前的代码是这样的......

common.vue

<template>
 <div>
   {{ page }}
 </div>
<template>

<script src="../scripts/test1.js"></script>

test1.js 的位置

export default {
  name: 'home',
  components: {
    test: test
  },
  data() {
    return {
        page: "test1",
    }
  }
}

但我还需要在我的 test2.js 中使用 common.vue。我无法分别导入这两个 .js。

在 Angular 中,我们可以编写绑定 .html 和 .js(在 ui.router 中)的休闲后期绑定

    .state('home', {
        url:'/',
        templateUrl: 'templates/home.html',
        controller: 'HomeController'
    })

有类似的吗?

【问题讨论】:

  • 分享任何现场演示?
  • @user2486,希望现在解释得更清楚。

标签: vue.js vue-component vue-router


【解决方案1】:

您可以通过id 属性共享模板。

Vue.component('my-comp1', {
  template: '#generic',
  data () {
    return {
      text: 'I am component 1'
    }
  }
})

Vue.component('my-comp2', {
  template: '#generic',
  data () {
    return {
      text: 'I am component 2'
    }
  }
})

new Vue({
  el: '#app'
})
<div id="app">
  <my-comp1></my-comp1>
  <my-comp2></my-comp2>
</div>

<template id="generic">
  <div>
    <p>{{ text }}</p>
  </div>
</template>

<script src="https://unpkg.com/vue"></script>

【讨论】:

  • 想强调的是,通常应避免将模板与组件定义分开。这是由于继承模板的组件和模板本身之间需要紧密耦合,因为组件的输出依赖于模板的接口。请参阅 guide on x-templates 了解 Vue 自己关于此模式的警告。 components 已经提供了一种重用机制,应该比 x-templates 更受青睐。
  • 我不以这种方式使用模板,也不建议以这种方式使用它们。
  • @WaldemarIce 那么如何复用需要不同功能的模板呢?有没有其他方法可以做到这一点??
  • 是的,我是。你可以使用槽,尤其是作用域槽,或者你可以使用类似 .
猜你喜欢
  • 2020-11-13
  • 2021-12-01
  • 1970-01-01
  • 2020-04-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 2019-11-29
相关资源
最近更新 更多