programing

VueJs 템플릿.외부 템플릿을 로드하는 방법

sourcejob 2023. 3. 10. 21:27
반응형

VueJs 템플릿.외부 템플릿을 로드하는 방법

Vue.js는 처음이라서 Angular을 써봤어요.JS는 한동안 다음과 같은 템플릿을 로드하는 데 사용되었습니다.

template: '/sometemplate.html',
controller: 'someCtrl'

이렇게 큰 HTML 템플릿을 JavaScript에 보관하는 대신 Vue에서는 어떻게 하면 좋을까요?

new Vue({
  el: '#replace',
  template: '<p>replaced</p>'
})

작은 템플릿은 괜찮지만 큰 템플릿은 실용적인가요?

Vue처럼 스크립트 태그 내에서 외부 템플릿 HTML을 로드하거나 HTML 템플릿을 사용하는 방법이 있습니까?

<script type="x-template" id="template">HTML template goes here</html>

스크립트 태그 템플릿을 참조하는 것만으로 사용할 수 있습니다.id.

{
  template: '#some-id'
}

단, 컴포넌트를 저장하기 위해 vueify(browserify를 사용하는 경우)orvue-loader(Webpack을 사용하는 경우)를 사용하는 것이 좋습니다..vue이런 파일들이요.

vue 파일

또, Vue의 작성자는, 외부 템플릿 URL 의 토픽에 관한 멋진 투고를 게재했습니다.

https://vuejs.org/2015/10/28/why-no-template-url/

다음과 같이 시험해 보십시오.
Vue2의 경우 : https://github.com/FranckFreiburger/http-vue-loader
Vue3의 경우 : https://github.com/FranckFreiburger/vue3-sfc-loader

예(Vue2) :

 new Vue({
        components: {
            'my-component': httpVueLoader('my-component.vue')
        },
        ...

예(Vue3) :

Vue.createApp({
  components: {
    'my-component': Vue.defineAsyncComponent(() => loadModule('./myComponent.vue', opts))
  },
  ...

데이비드, 좋은 예이긴 한데 DOM을 컴파일하려면 어떻게 해야 할까요?

https://jsfiddle.net/q7xcbuxd/35/

위의 예시와 같이 비동기 동작을 시뮬레이트하면 동작합니다.그러나 외부 페이지를 "온 더 플라이" 로딩하면 DOM이 준비되지 않았다고 Vue가 불평합니다.자세한 내용은 다음과 같습니다.Uncaught TypeError: Cannot set property 'vue' of undefined전화하는 것보다 더 좋은 방법이 있을까요?$compile페이지가 로드되었을 때?와 함께 시도했습니다.$mount하지만 그것은 도움이 되지 않았다.

업데이트: 괜찮습니다.이제 방법을 알게 되었습니다.

Vue.component('async-component', function (resolve, reject) {
    vue.$http.get('async-component.html', function(data, status, request){
        var parser = new DOMParser();
        var doc = parser.parseFromString(data, "text/html");
        resolve({
            template: doc
        });
    });
});

그리고 실제 템플릿에서는

<script id="someTemplate" type="text/x-template"></script>

태그를 지정하고 html만 포함합니다.

(이 솔루션에서는http loader가 https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.1.10/vue-resource.min.js) 에서 필요합니다.

http-vue-loader를 사용해 봤는데 잘 작동합니다.이 라이브러리는 사용하기 쉽고 문서와 예시가 잘 되어 있습니다.

파일에서 직접 템플릿을 로드할 수는 없지만 별도의 단일 파일 구성 요소에 html을 유지할 수 있습니다.건너뛸 수도 있습니다.<script>...</script>일부.

사용방법(로더 매뉴얼 참조)

my-component.vue

<template>
    <div class="hello">Hello {{who}}</div>
</template>

index.html

<!doctype html>
<html lang="en">
  <head>
    <script src="https://unpkg.com/vue"></script>
    <script src="https://unpkg.com/http-vue-loader"></script>
  </head>

  <body>
    <div id="my-app">
      <my-component></my-component>
    </div>

    <script type="text/javascript">
      new Vue({
        el: '#my-app',
        components: {
          'my-component': httpVueLoader('my-component.vue')
        }
      });
    </script>
  </body>
</html>

두 파일 모두 동일한 수준의 한 폴더에 저장해야 합니다.

1. Vue 2.x에서는 .vue 파일을 사용하는 대신 Import 순서를 반대로 하는 것이 좋습니다.

// template.vue
<template>
  <div class="helloworld">
      <h1>Hello world</h1>
  </div>
</template>

<script>
  import src from './src'
  export default src
</script>

및 다른 파일로

// src.js
export default {
  name: 'helloworld',
  props: {},
  ...
}

다음으로 컴포넌트 등록에서

import helloworld from './helloworld/template.vue'

new Vue({
 components: {
 'helloworld': helloworld
},
...})

이렇게 하면 두 가지 장점을 모두 얻을 수 있으므로 문자열 내에서 템플릿을 강제로 작성할 필요가 없습니다.

2. 느긋하게 로드하려면 Vue 2.x에서 그렇게 하는 방법이 있다고 합니다.

new Vue({
 components: {
 'helloworld': () => import(/* webpackChunkName: "helloworld" */ './helloworld/template.vue')
},
...})

그러면 브라우저에서 해당 페이지의 요청에 따라 hellowolld.js(모든 컴포넌트 코드를 포함)가 로드됩니다.

위의 를 ES6와 함께 을 전제로 하고 .import 설명

빌 크리스웰이 이미 언급한 (x-템플릿)에서 당신이 원하는 것을 달성하는 방법은 적어도 두 가지가 있지만, 나는 예를 추가할 가치가 있다고 생각한다.

  1. 다음과 같이 컴포넌트를 정의합니다.

    Vue.component('my-checkbox', { // id of x-template template: '#my-template' });

  2. x-template를 사용하여 html 파일을 추가합니다(ID는 컴포넌트에서 지정한 것과 일치해야 합니다).

    <script type="text/x-template" id="my-template">...</script>

또 다른 접근법(이 방법이 더 좋습니다)은 인라인 템플릿을 사용하는 것입니다.

  1. 템플릿을 다음과 같이 정의합니다.

    Vue.component('my-template', {});

  2. 컴포넌트와 템플릿이 포함된html 파일 추가

    <my-template inline-template>place for your html</my-template>

꼭 추가해 주세요.inline-template 동작하지 않습니다.Attribute, Attribute, Attribute는 동작하지

슈퍼에이전트에서는 다음 방법을 사용할 수 있습니다.

var promise = superagent.get("something.html")
    .end(function (error, response) {
        if (error) {
            console.error("load of something.html failed", error));
            return;
        }

        var parser = new DOMParser()
        var doc = parser.parseFromString(response.text, "text/html");
        document.body.appendChild(doc.scripts[0]);
    });

네 것을 넣어라.<script> .something.html를 참조해 주세요.

jQuery를 사용하는 경우 .load가 작동합니다.

Vue가 문제의 DOM을 컴파일하기 전에 이 작업을 완료해야 합니다.또는 $mount를 사용하여 수동으로 설정합니다.

다음과 같이 browserify를 사용하여 모든 것을 번들합니다.

//Home.js

import Vue from 'vue';

var Home = Vue.extend({
    template: require('./Home.vue')
});

export default Home;

//Home.vue
<h1>Hello</h1>

// And for your browserify bundle use a transform called stringify

... .transform(stringify(['.html', '.svg', '.vue', '.template', '.tmpl']));

언급URL : https://stackoverflow.com/questions/31633573/vuejs-templating-how-to-load-external-templates

반응형