简体   繁体   中英

Assigning a Template to a Vue Class Component

How does one assign a template to a Vue class component directly? In the example below, I can render the subcomponent as a node, but never renders the template. I've tried to assign the template many different ways to get it to render, but nothing seems to work:

<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>

Note I'm also having the same issue if I use a Vue.component directly:

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

Looks like your code is ok. Check that you are using fresh versions of packages and your configs.

I've just created new project with

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

After integrating your code to newly created project, I've realized that all is working correctly:

<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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM