我试过这个:
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)。
Vue.createApp({template:'<my-component></my-component>'})
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>