如何在 Vue2 中通过 HTML 运行组件的方法



我有一个.vue文件ServiceList,它导入组件Information.vue。我想在ServiceList的模板中循环运行Information的代码,如下所示:

ServiceList.vue
<template>
<div> 
<h1>Headline</h1>
<div v-for="service in services">
<h2>{{ service.name }}</h2>
<information v-bind:service="service"/>
</div>
</div>
</template>
<script>
import Information from './Information'
... (more components here)
export default {
components: {
Information,
... (more components here)
},
... (rest of export here)
}
</script>

这就是Information的样子:

Information.vue
<template>
<div>
<p v-bind:id="'info'+service.id"/>      
</div>  
</template>
<script>
export default {
props:['service'],
data: function () {
return {
services: this.$store.state.Services.data
}
},
methods: {
getInfo: function (service) {
var info = '<b>Servicename:</b> <br>';
info += service.name;
... (method adds more to 'info' here)
document.getElementById('info'+service.id).innerHTML = info;
}
}
}
</script>

我试过做之类的事情

<template>
<div>
<p v-bind:id="'info'+service.id"/>  
{{ getInfo(service) }}  
</div>  
</template>

但它似乎从来都不起作用。奇怪的是,当我把它做成一个按钮时,

<template>
<div>
<button v-on:click="getInfo(service)">GET INFO</button> 
<p v-bind:id="'info'+service.id"/>
</div>  
</template>

它工作得很好!但我不想要按钮,我只想它出现。

对于这种琐碎的情况,您不需要在Vue js中操作DOM,只需添加所有想要模板化的内容并删除getInfo方法,例如:

Information.vue
<template>
<div>
<p>
<b>Servicename:</b> <br>
{{ service.name }}<br>
<b>Another Field:</b> <br>
{{ service.anotherField }}<br>
<b>Another Field 2 :</b> <br>
{{ service.anotherField2 }}<br>
</p>      
</div>  
</template>

或者如果真的想使用html,请执行以下操作:

Information.vue
<template>
<div>
<p v-html="getInfo(service)"/>      
</div>  
</template>
<script>
export default {
props:['service'],
data: function () {
return {
services: this.$store.state.Services.data
}
},
methods: {
getInfo: function (service) {
if (!service) return '';
var info = '<b>Servicename:</b> <br>';
info += service.name;
... (method adds more to 'info' here)
return info;
}
}
}

最新更新