在 vue 2 中v-html需要渲染一个额外的包装标签。但我正在尝试类似以下的事情。
<select v-model="coutnry">
// here the options to be rendered.
</select>
<script>
...
data()}{
return{
countryTags:`<option value="BD">Bangladesh</option>`
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
因为,在这里我无法渲染任何额外的 html 标签,我累了<template v-html="countryTags">,但这不起作用。stackoverlflow 周围的另一个解决方案似乎有点令人困惑。正确的解决方案是什么?
不幸的是,Vue 没有提供一种简单的方法来完成此任务(有关原因的更多详细信息可以在这里找到: https: //github.com/vuejs/vue/issues/7431)
正如那里所解释的,您可以创建一个功能组件来仅渲染 HTML,而无需包装元素:
Vue.component('html-fragment', {
functional: true,
props: ['html'],
render(h, ctx) {
const nodes = new Vue({
beforeCreate() { this.$createElement = h }, // not necessary, but cleaner imho
template: `<div>${ctx.props.html}</div>`
}).$mount()._vnode.children
return nodes
}
})
Run Code Online (Sandbox Code Playgroud)
该组件由 Vue 核心成员 (LinusBorg) 创建:https ://jsfiddle.net/Linusborg/mfqjk5hm/
| 归档时间: |
|
| 查看次数: |
6093 次 |
| 最近记录: |