How to use x-template to separate out template from Vue Component

Viewed 13693

Tried to separate out template from Vue Component as below but it does not work. Referencing only vue.js file and not browsify.

Vue.component('my-checkbox', {
    template: '#checkbox-template',
    data() {
        return { checked: false, title: 'Check me' }
    },
    methods: {
        check() { this.checked = !this.checked; }
    }
});

<script type="text/x-template" id="checkbox-template">
    <div class="checkbox-wrapper" @click="check">
        <div :class="{ checkbox: true, checked: checked }"></div>
        <div class="title"></div>
    </div>
</script>

Or any alternate way to separate out template from vue component.

2 Answers

You define X-Templates in your HTML file. See below for a brief demo

// this is the JS file, eg app.js
Vue.component('my-checkbox', {
    template: '#checkbox-template',
    data() {
        return { checked: false, title: 'Check me' }
    },
    methods: {
        check() { this.checked = !this.checked; }
    }
});

new Vue({el:'#app'})
/* CSS file */
.checkbox-wrapper {
  border: 1px solid;
  display: flex;
}
.checkbox {
  width: 50px;
  height: 50px;
  background: red;
}
.checkbox.checked {
  background: green;
}
<!-- HTML file -->
<script src="https://cdn.jsdelivr.net/npm/vue@2.5.17/dist/vue.min.js"></script>
<script type="text/x-template" id="checkbox-template">
    <div class="checkbox-wrapper" @click="check">
        <div :class="{ checkbox: true, checked: checked }"></div>
        <div class="title">{{ title }}</div>
    </div>
</script>
<div id="app"> <!-- the root Vue element -->
  <my-checkbox></my-checkbox> <!-- your component -->
</div>

Sorry for my bad english it's not my main language!

Try it!

You need generate two file in same directory:

  • path/to/checkboxComponent.vue
  • path/to/checkboxComponent.html

In checkboxComponent.vue file

<script>
// Add imports here eg:
// import Something from 'something';
export default {
    template: require('./checkboxComponent.html'),
    data() {
        return { checked: false, title: 'Check me' }
    },
    methods: {
        check() { this.checked = !this.checked; }
    }
}
</script>

In checkboxComponent.html file

<template>
    <div class="checkbox-wrapper" @click="check">
        <div :class="{ checkbox: true, checked: checked }"></div>
        <div class="title"></div>
    </div>
</template>

Now you need to declare this Component in same file you declare Vue app, as the following:

Vue.component('my-checkbox', require('path/to/checkboxComponent.vue').default);

In my case

I have three files with these directories structure:

js/app.js
js/components/checkboxComponent.vue
js/components/checkboxComponent.html

In app.js, i'm declare the Vue app, so the require method path need to start with a dot, like this:

Vue.component('my-checkbox', require('./components/checkboxComponent.vue').default);
Related