marked在vue项目中改变超链接跳转方式和图片放大预览
这里我是另起一个js文件对marked的配置做了修改,参考如下
import marked from 'marked'
let renderer = new marked.Renderer()
const linkRenderer = renderer.link
const imgRenderer = renderer.image
// 超链接使用新窗口打开
renderer.link = (href, title, text) => {const html = linkRenderer.call(renderer, href, title, text)return html.replace(/^<a /, '<a target="_blank" ')
}// marked解析过程中解析到图片的回调,为每个img标签绑定点击事件,并传递当前事件以及href图片链接
renderer.image = function (href, title, text) {const img = imgRenderer.call(renderer, href, title, text)// 在图片元素上添加点击事件处理函数return `<img width="800" height="500" οnclick="showMarkedImage('${href}')" src="${href}" alt="${text}" title="${title ? title : ''}">`
}
marked.setOptions({renderer,sanitize: false
})export default marked
然后在vue文件中进行进行该文件的引用
// vue结构
<div class="show-inputText" v-html="markedContent(form.inputText)"></div>
<el-image v-show="imgPreviewUrl" style="display: none" ref="previewImg" :src="imgPreviewUrl" :preview-src-list="imgList">
</el-image>
// script结构
import marked from '上述文件的路径'data() {return {form: {inputText: '',},imgPreviewUrl: '',imgList: []}}},
最后格式化markdown文本
init() {// 获取markdown文本中所有的图片链接this.getImgList(item.inputText)// markdown图片放大预览let _this = thiswindow.showMarkedImage = function (url) {_this.imgPreviewUrl = url_this.$nextTick(() => {_this.$refs.previewImg.showViewer = true// 需要把当前的图片放到最前面,后面排序let copyImgList = [..._this.imgList]let targetUrlIndex = copyImgList.findIndex(item => item == url)copyImgList.splice(targetUrlIndex, 1)let res = [url, ...copyImgList]_this.$refs.previewImg.previewSrcList = res_this.$refs.previewImg.src = url}, 200)},// 获取图片getImgList(inputText) {// 匹配markdown文案中所有的图片,以便后续放大预览const regex = /!\[Image\]\((.*?)\)/gconst matches = inputText.match(regex)let res = []if (matches) {for (const match of matches) {const imageUrl = match.match(/\((.*?)\)/)[1]res.push(imageUrl)}}this.imgList = res},// markdown格式化markedContent(markdownContent) {let mak = marked.marked(markdownContent)if (mak.substr(-1) == '\n') {mak = mak.slice(0, -1)}return mak},