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.
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/[email protected]/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:
<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>
<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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With