Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>'
})
like image 490
fny Avatar asked Jan 16 '18 19:01

fny


People also ask

How do I use Vue component template?

The quickest and easiest way to define a Vue component template is to add a template property to the component definition and assign a regular string containing your markup.

What is Vue component template?

Vue uses an HTML-based template syntax that allows you to declaratively bind the rendered DOM to the underlying component instance's data. All Vue templates are syntactically valid HTML that can be parsed by spec-compliant browsers and HTML parsers.

What does template tag do in Vue?

In Vue, templating is the main way we create reusable components. We can use templates to take data, and turn it into real elements on a screen that users can see.

How do I add a class to my Vue component?

Adding a dynamic class name is as simple as adding the prop :class="classname" to your component. Whatever classname evaluates to will be the class name that is added to your component. Join 11,067 other Vue devs and get exclusive tips and insights delivered straight to your inbox, every week.


1 Answers

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>
like image 121
Skyway Skyway Avatar answered Oct 04 '22 00:10

Skyway Skyway