IT이야기

x-template를 사용하여 템플릿을 Vue 구성 요소에서 분리하는 방법

cyworld 2022. 7. 25. 22:35
반응형

x-template를 사용하여 템플릿을 Vue 구성 요소에서 분리하는 방법

아래와 같이 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>

또는 템플릿을 vue 컴포넌트에서 분리할 수 있습니다.

X-Template는 HTML 파일에서 정의합니다.간단한 데모는 아래를 참조해 주세요.

// 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>

영어가 서툴러서 미안해 내 주요 언어가 아니야!

해봐!

같은 디렉토리에 2개의 파일을 생성해야 합니다.

  • path/to/checkbox Component.표시하다
  • path/to/checkbox Component.html

체크박스 컴포넌트vue 파일

<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 checkbox Component.html 파일

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

이제 Vue app을 선언한 파일과 동일한 파일에서 다음과 같이 이 구성 요소를 선언해야 합니다.

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

저 같은 경우에는

다음의 디렉토리 구조의 파일이 3개 있습니다.

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

app.js에서는 Vue 앱을 선언하기 때문에 필요한 메서드 경로는 다음과 같이 점으로 시작해야 합니다.

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

언급URL : https://stackoverflow.com/questions/52295908/how-to-use-x-template-to-separate-out-template-from-vue-component

반응형