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>

1

2 Answers 2

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>

Sign up to request clarification or add additional context in comments.

3 Comments

Also use the JavaScript debug console to catch errors, such as one root element in the template
Thank you my friend. Cheers
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.
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,
  },
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.