动态加载VueJS模板

问题描述 投票:0回答:1
  • 模板是从外部位置完全下载的(包括根元素)
  • 模板可以包含绑定
  • 组件被注册为自定义元素

我试过这个:

async function getTemplate() {
  const response = `
    <div>
      <h1>{{ message }}</h1>
    </div>
  `;

  return await Promise.resolve(response);
}

const MyCustomElement = {
  data() {
    return {
      template: null,
      message: 'Hello, I am a Vue component!'
    };
  },
  async created() {
    this.template = await getTemplate();
  },
  render() {
    if (this.template == null)
        return Vue.h('div', 'Loading...');

    return Vue.h(Vue.compile(this.template)); // ERROR!
  }
};

const element = Vue.defineCustomElement(MyCustomElement);

customElements.define('my-component', element);

Vue.createApp({}).mount('#app');

它说消息未定义。有什么想法为什么找不到定义的属性吗?
是否应该以其他方式实施?
这是 VueJS 3,最新的(3.4.25)。

vuejs3
1个回答
0
投票
  1. 您应该使用以下元素创建应用程序:
    Vue.createApp({template:'<my-component></my-component>'})
  2. Vue.h
    应该使用传递给模板的 props 来提供
    Vue.h(Vue.compile(this.template), {message: this.message})
    :

async function getTemplate() {
  const response = `
    <div>
      <h1>{{ message }}</h1>
    </div>
  `;

  return new Promise(r => setTimeout(() => r(response), 500));
}

const MyCustomElement = {
  data() {
    return {
      template: null,
      message: 'Hello, I am a Vue component!'
    };
  },
  async created() {
    this.template = await getTemplate();
  },
  render() {
    if (this.template == null)
        return Vue.h('div', 'Loading...');

    return Vue.h(Vue.compile(this.template), {message: this.message}); // ERROR!
  }
};

const element = Vue.defineCustomElement(MyCustomElement);

customElements.define('my-component', element);

Vue.createApp({template:'<my-component></my-component>'}).mount('#app');
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.4.8/vue.global.min.js"></script>
<div id="app"></div>

© www.soinside.com 2019 - 2024. All rights reserved.