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"> <div @click="check"> <div :class="{ checkbox: true, checked: checked }"></div> <div></div> </div> </script> Or any alternate way to separate out template from vue component.
22 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=""></script> <script type="text/x-template"> <div @click="check"> <div :class="{ checkbox: true, checked: checked }"></div> <div>{{ title }}</div> </div> </script> <div> <!-- the root Vue element --> <my-checkbox></my-checkbox> <!-- your component --> </div>0Sorry 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 @click="check"> <div :class="{ checkbox: true, checked: checked }"></div> <div></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); 1