如何使用 x-template 从 Vue 组件中分离出模板

use*_*357 4 vue.js xtemplate vue-component vuejs2

试图从 Vue 组件中分离出模板,如下所示,但它不起作用。仅引用 vue.js 文件而不是浏览。

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>
Run Code Online (Sandbox Code Playgroud)

或者任何将模板与 vue 组件分离的替代方法。

Phi*_*hil 8

您可以在 HTML 文件中定义X-Templates。请参阅下面的简要演示

// 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'})
Run Code Online (Sandbox Code Playgroud)
/* CSS file */
.checkbox-wrapper {
  border: 1px solid;
  display: flex;
}
.checkbox {
  width: 50px;
  height: 50px;
  background: red;
}
.checkbox.checked {
  background: green;
}
Run Code Online (Sandbox Code Playgroud)
<!-- 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>
Run Code Online (Sandbox Code Playgroud)