将模板分配给Vue类组件

时间:2018-01-16 19:54:25

标签: javascript typescript vue.js

如何直接将模板分配给Vue类组件?在下面的示例中,我可以将子组件渲染为节点,但从不渲染模板。我试图给模板分配许多不同的方式来渲染它,但似乎没有任何效果:

<template>
  <div>
    <p>This should render one, two, three below twice.</p>
    <div v-for="item in items" :key="item">
      {{ item }}
      <Subcomponent :item="item" />
    </div>
  </div>
</template>

<script lang="ts">
  import { Vue, Component, Prop } from 'vue-property-decorator'

  @Component({ template:`<span>{{item}}</span>` })
  class Subcomponent extends Vue {
    template = `<span>{{ item }}</span>`
    @Prop({required: true})
    item: string
  }

  @Component({ components: { Subcomponent } })
  export default class Test extends Vue {
    items = ['one', 'two', 'three']
  }
</script>

注意如果我直接使用Vue.component,我也会遇到同样的问题:

Vue.component('Subcomponent', {
  props: ['item'],
  template: '<span>{{item}}</span>'
})

1 个答案:

答案 0 :(得分:1)

看起来你的代码还可以。 检查您是否使用了新版本的软件包和配置。

我刚用

创建了新项目

vue init ducksoupdev/vue-webpack-typescript my-project

在将代码集成到新创建的项目之后,我意识到一切正常:

<div><p>This should render one, two, three below twice.</p> <div>
      one
      <span>one</span></div><div>
      two
      <span>two</span></div><div>
      three
      <span>three</span></div></div>
相关问题