如何解决在vue中嵌入模板
我想在VueJS中使用本地组件:
我的组件文件(清理了一下):
<template id="herovaluePair">
<td class="inner label">{{label}}</td>
<td class="inner value">{{c}}</td>
<td class="inner value">
{{t}}
<span v-if="c < t" class="more">(+{{t-c}})</span>
<span v-if="c > t" class="less">({{t-c}})</span>
</td>
</template>
<template id="hero">
<table class="hero card" border="0" cellpadding="0" cellspacing="0">
<tr>
<td>other data...</td>
</tr>
<tr>
<hvp label="Label" v-bind:c="current.level" :t="target.level" :key="hero.id"/>
</tr>
</table>
</template>
<script>
var HerovaluePair = {
template: "#herovaluePair",props: {
label : String,c : Number,t : Number
},created() {
console.log("HVP: "+this.c+" "+this.t);
}
};
Vue.component("Hero",{
template: "#hero",props: {
heroId : String
},components: {
"hvp" : HerovaluePair
},data: () => ({
hero: {},current: {},target: {}
}),computed: {
},created() {
fetch("/api/hero/"+this.heroId)
.then(res => res.json())
.then(res => {
this.hero = res.hero
this.current = res.current
this.target = res.target
})
}
});
</script>
<style>
</style>
此外部Hero模板用于列表迭代器:
<template id="card-list">
<table>
Card list
<div id="">
<div v-for="card in cards" class="entry">
<Hero :hero-id="card.hero.id" :key="card.hero.id"/>
</div>
</div>
</table>
</template>
<script>
Vue.component("card-list",{
template: "#card-list",data: () => ({
cards: [],}),created() {
fetch("/api/cards")
.then(res => res.json())
.then(res => {
this.cards = res.heroes
})
.catch((e) => alert("Error while fetching cards: "+e));
}
});
</script>
<style>
</style>
但是,当我渲染卡片列表时,它仅生成td
模板中第一个hvp
的列表:
当我注释掉hpv
的调用时,页面将使用Hero模板中的所有HTML代码正确呈现。
我试图找出我遗漏的步骤,但找不到线索。 最后一个信息:我使用JavalinVue支持服务器端,而不是基于nodejs的Vue CLI。我不知道它是否有影响,但可能很重要。
更新1
在IVO GElov发现具有多个根标记的问题之后,并且由于无法移至Vue3,我尝试按照他的建议将其作为功能模板。我删除了模板并创建了render
函数:
var HerovaluePair = {
template: "#herovaluePair",functional: true,render(createElement,context) {
console.log("HVP: "+context.props.c+" "+context.props.t);
if (typeof context.props.c === undefined) return createElement("td" )
else return [
createElement("td",context.props.label ),createElement("td",context.props.c ),context.props.t )
]
}
}
尽管控制台指示正确调用了渲染,但结果是相同的:既没有渲染的节点,也没有显示父Hero组件。我尝试移入其他文件,尝试使用功能模板格式,但没有用。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。