1

I've been struggling for a week now trying to understand how the Vue component work within a Twig file with x-template.

I've test my code for number of time without any luck.

new Vue ({
 el: '#app',
 data: function () {
   return {
      fname: 'John',
      lname: 'Smith'
   }
 }
});

new Vue ({
 template: '#my-template',
 data: function () {
   return {
     fname: 'Paul',
     lname: 'Smith'
   }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<script type="text/x-template" id="my-template">
<div>Hello world</div>
<div>{{ fname }}</div>
</script>

<div id="app">
<h1>Test</h1>
<my-template></my-template>
</div>
mana
  • 1,075
  • 1
  • 24
  • 43

2 Answers2

1

If you are initializing Vue and want to use a component in it, you must register it. Component name and template ID are also two different things.

Vue.component('my-template', {
  template: '#my-html-template',
  data: function() {
    return {
      fname: 'Paul',
      lname: 'Smith'
    }
  }
})

new Vue({
  el: '#app',
  data: function() {
    return {
      fname: 'John',
      lname: 'Smith'
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<script type="text/x-template" id="my-html-template">
  <div>
    <div>Hello world</div>
    <div>{{ fname }}</div>
  </div>
</script>

<div id="app">
  <h1>Test</h1>
  <my-template></my-template>
</div>
Gander
  • 1,854
  • 1
  • 23
  • 30
  • 1
    Also use the JavaScript debug console to catch errors, such as one root element in the template – Gander Dec 06 '19 at 10:31
  • Thank you my friend. Cheers – mana Dec 06 '19 at 10:56
  • I just want to put down this, might help someone. Take note inside the "script" tag content. It has to be a one root element that wrap the content. For example - it has to have a "div" tag that wrap all the elements inside your "script" tag. Other wise you will have an error. – mana Dec 06 '19 at 11:01
1

How about this setup? https://codepen.io/fuleinist/pen/KKwdwdp

<script type="text/x-template" id="my-template">
<div>Hello world</div>
<div>{{ lname }}</div>
</script>


<div id="app">
  <my-template></my-template>
</div>

Then in your js file

var myTemplate = Vue.component('my-template', {
 template: '#my-template',
 props: {
    fname: String,
    lname: String,
},
 data: function () { 
   return {
     fname: 'John',
     lname: 'Smith'
   }
 },
 });

new Vue({
  el: '#app',
  components: {
    myTemplate: myTemplate,
  },
})
Chris Chen
  • 1,228
  • 9
  • 14