gpt4 book ai didi

javascript - Vue动态加载组件并突出显示代码预览并保留HTML结构

转载 作者:行者123 更新时间:2023-12-02 21:55:26 25 4
gpt4 key购买 nike

我正在尝试动态加载 vue 组件,当组件可见时,它应该将组件的 HTML 显示为代码预览。

这是成功的并且正在工作,但显示了一个大字符串,因为我使用 $el.innnerHTML。我想要的是组件/html 的结构应该反射(reflect)在代码预览中。

这是现在的结果:

enter image description here

我想要什么:

enter image description here

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/prism/1.14.0/themes/prism.min.css" />
</head>

<body>
<div id="app" class="container mt-5">
<div class="row">
<div class="col-12">

<select v-model="selected" @change="onChange">
<option disabled value="">Please select one</option>
<option value="componentOne">A</option>
<option value="componentTwo">B</option>
</select>

<component :is="selected" :ref="mychildcomponent"></component>
<code-highlight :code="codeHighlight"></code-highlight>

</div>
</div>
</div>

<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/prism/1.14.0/prism.min.js"></script>

<script>
Vue.component("componentOne", {
template: `
<div>
<div>
<p>Home component</p>
</div>
</div>
`
});

Vue.component("componentTwo", {
template: `
<div>
<div>
<p>Posts component</p>
</div>
</div>
`
});

Vue.component("code-highlight", {
props: ["code"],
template: "<pre class='language-markup'><code class='language-markup' v-html='highlightedCode'></code></pre>",
computed: {
highlightedCode: function () {
return Prism.highlight(this.code, Prism.languages.javascript);
}
},
});

new Vue({
el: "#app",
data: {
selected: "",
mychildcomponent: "mychildcomponent",
codeHighlight: ""
},
methods: {
onChange() {
setTimeout(() => {
this.codeHighlight = this.$refs.mychildcomponent.$el.innerHTML;
})
}
}
});
</script>
</body>

</html>

示例

Here is a JSFiddle

最佳答案

您可以使用<pre>标签如:

Vue.component("componentOne", {
template: `
<pre>
<div>
<p>Home component</p>
</div>
</pre>
`
});

<PRE>标签将按原样显示网页上的文本。

关于javascript - Vue动态加载组件并突出显示代码预览并保留HTML结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60025546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com