【发布时间】:2018-12-24 19:28:07
【问题描述】:
我有一个带有一些 html 的#app 容器,我在 #app 上创建了 Vue 实例,所有内容都被编译并转换为 Vuejs 组件。 然后我在另一个 html 字符串中进行 ajax,我需要以某种方式将其编译成组件,我该怎么做?
【问题讨论】:
标签: vue.js vue-component
我有一个带有一些 html 的#app 容器,我在 #app 上创建了 Vue 实例,所有内容都被编译并转换为 Vuejs 组件。 然后我在另一个 html 字符串中进行 ajax,我需要以某种方式将其编译成组件,我该怎么做?
【问题讨论】:
标签: vue.js vue-component
这就是 template 选项的用例,它可以在您的 DOM 中引用具有特定 ID 的 <template>(就像您使用 el 选项对您的应用所做的那样),或者直接引用您的 HTML 模板:
Vue.component({
template: `<span class="myItem"><slot></slot></span>`
});
您可以通过向组件列表提供一个函数来轻松地将其转换为 Async Component,该函数返回一个使用组件构造函数解析的 Promise(例如,使用 Vue.extend):
const MyLoadingComponent = Vue.extend({
template: '#my-loading',
});
new Vue({
el: '#app',
data() {
return {
items: [],
};
},
components: {
'my-component': loadComponentWithLoading,
},
methods: {
addItem() {
this.items.push(Math.random());
},
},
});
// https://vuejs.org/v2/guide/components-dynamic-async.html#Handling-Loading-State
function loadComponentWithLoading() {
return {
component: loadComponent(),
loading: MyLoadingComponent,
};
}
// https://vuejs.org/v2/guide/components-dynamic-async.html#Async-Components
function loadComponent() {
return new Promise(function(resolve, reject) {
loadComponentHtml().then((html) => {
resolve(Vue.extend({
// https://vuejs.org/v2/api/#template
template: html,
}));
});
});
}
function loadComponentHtml() {
return new Promise(function(resolve, reject) {
setTimeout(() => {
resolve(`<span class="myItem"><slot></slot></span>`);
}, 2000);
});
}
.myItem {
color: green;
}
.myLoading {
font-style: italic;
color: red;
}
<script src="https://unpkg.com/vue@2"></script>
<div id="app">
<button @click.prevent="addItem">Add some list items</button>
<ul>
<li v-for="item of items">
<my-component>{{item}}</my-component>
</li>
</ul>
</div>
<template id="my-loading">
<span class="myLoading">Loading…</span>
</template>
【讨论】:
这样的事情在 Vue 中不被认为是一个好的做法,但你实际上可以使用 Vue with template compiler 动态创建组件。
通常,Vue 的 stand-alone 分发版中,您只需在页面中包含一个脚本标记,就已经包含一个模板编译器。
【讨论】: