vue实现预览效果
Vue 实现预览效果的方法
在 Vue 中实现预览效果可以通过多种方式完成,以下是几种常见的实现方法:
使用动态组件或条件渲染
通过 v-if 或 v-show 控制预览内容的显示与隐藏。结合数据绑定动态更新预览内容。

<template>
<div>
<textarea v-model="content" placeholder="输入内容"></textarea>
<div class="preview" v-html="compiledContent"></div>
</div>
</template>
<script>
export default {
data() {
return {
content: ''
}
},
computed: {
compiledContent() {
return this.content // 可添加 Markdown 或 HTML 解析逻辑
}
}
}
</script>
结合第三方库实现富文本预览
使用如 marked(Markdown 解析)或 DOMPurify(HTML sanitize)实现安全预览。
import marked from 'marked';
import DOMPurify from 'dompurify';
computed: {
compiledContent() {
return DOMPurify.sanitize(marked(this.content));
}
}
文件上传预览
对于图片或文件上传的预览,可通过 URL.createObjectURL 生成临时链接。

<template>
<input type="file" @change="handleFileChange">
<img v-if="previewUrl" :src="previewUrl" alt="预览">
</template>
<script>
export default {
data() {
return {
previewUrl: ''
}
},
methods: {
handleFileChange(e) {
const file = e.target.files[0];
this.previewUrl = URL.createObjectURL(file);
}
}
}
</script>
使用弹窗或全屏预览
通过组件封装实现弹窗预览,例如结合 element-ui 的 Dialog。
<el-button @click="showPreview = true">预览</el-button>
<el-dialog :visible.sync="showPreview">
<div v-html="compiledContent"></div>
</el-dialog>
实时编辑与预览分屏
利用 CSS 布局实现类似 Markdown 编辑器的分屏效果。
<div class="editor-container">
<textarea v-model="content"></textarea>
<div class="preview-pane" v-html="compiledContent"></div>
</div>
<style>
.editor-container {
display: flex;
}
textarea, .preview-pane {
width: 50%;
height: 300px;
}
</style>
注意事项
- 安全性:直接使用
v-html时需防范 XSS 攻击,建议用DOMPurify过滤内容。 - 性能:频繁更新的预览内容可考虑使用防抖(
debounce)优化。 - 销毁处理:通过
URL.createObjectURL生成的链接需在组件销毁时手动释放(URL.revokeObjectURL)。






