javascript - Vue.js 插槽 - 如何在计算属性中检索插槽内容
问题描述
我对vue.js 插槽有疑问。一方面,我需要显示插槽代码。另一方面,我需要在 textarea 中使用它来将其发送到外部源。
主.vue
<template>
<div class="main">
<my-code>
<template v-slot:css-code>
#custom-css {
width: 300px
height: 200px;
}
</template>
<template v-slot:html-code>
<ul id="custom-css">
<li> aaa </li>
<li> bbb </li>
<li> ccc </li>
</ul>
</template>
</my-code>
</div>
</template>
我的代码.vue
<template>
<div class="my-code">
<!-- display the code -->
<component :is="'style'" :name="codeId"><slot name="css-code"></slot></component>
<slot name="html-code"></slot>
<!-- send the code -->
<form method="post" action="https://my-external-service.com/">
<textarea name="html">{{theHTML}}</textarea>
<textarea name="css">{{theCSS}}</textarea>
<input type="submit">
</form>
</div>
</template>
<script>
export default {
name: 'myCode',
props: {
codeId: String,
},
computed: {
theHTML() {
return this.$slots['html-code']; /* The problem is here, it returns vNodes. */
},
theCSS() {
return this.$slots['css-code'][0].text;
},
}
}
</script>
问题是 vue 不会转槽内容。<VNode>
它是一个元素数组。有没有办法在textarea
. 或者一种在theHTML()
计算属性中检索槽内容的方法。
注意:我在 vuePress 中使用这个组件。
解决方案
您需要创建自定义组件或自定义函数来将 VNode 直接渲染为 html。我认为这将是最简单的解决方案。
vnode 到 html.vue
<script>
export default {
props: ["vnode"],
render(createElement) {
return createElement("template", [this.vnode]);
},
mounted() {
this.$emit(
"html",
[...this.$el.childNodes].map((n) => n.outerHTML).join("\n")
);
},
};
</script>
然后你可以将它用于你的组件
template>
<div class="my-code">
<!-- display the code -->
<component :is="'style'" :name="codeId"
><slot name="css-code"></slot
></component>
<slot name="html-code"></slot>
<!-- send the code -->
<Vnode :vnode="theHTML" @html="html = $event" />
<form method="post" action="https://my-external-service.com/">
<textarea name="html" v-model="html"></textarea>
<textarea name="css" v-model="theCSS"></textarea>
<input type="submit" />
</form>
</div>
</template>
<script>
import Vnode from "./vnode-to-html";
export default {
name: "myCode",
components: {
Vnode,
},
props: {
codeId: String,
},
data() {
return {
html: "", // add this property to get the plain HTML
};
},
computed: {
theHTML() {
return this.$slots[
"html-code"
]
},
theCSS() {
return this.$slots["css-code"][0].text;
},
},
};
</script>
这个线程可能有助于如何将 html 模板作为道具传递给 Vue 组件
推荐阅读
- css - 在 Wordpress 中编辑导航栏链接的字体大小?
- android - 如何从我运行到 ListView Android 的命令中显示数据?
- bash - 重定向命令输出时,Bash 不评估变量
- javascript - AngularJS Formly ui-mask:删除模型的输入掩码字符
- pyspark - 更改列名称时,AWS Glue 作业失败并出现 OOM 异常
- javascript - 我可以将对象推送到 Vue 组件数据中吗?想要在 js 过滤/操作之后做一个表
- ultraedit - UltraEdit 脚本使用 saveAs("^c")
- python - 遍历熊猫数据框/系列的特定列
- mysql - 如何从具有不同但条件字段的 2 个表中选择记录?
- java - 需要帮助单击阴影根(关闭)类型下的元素