vue-photo-preview基于photoswipe的vue图片预览组件 vue-photo-preview 示例
1、安装 vue-photo-preview
npm install vue-photo-preview --save
2、在main.js引入插件
import preview from 'vue-photo-preview';
import 'vue-photo-preview/dist/skin.css';
Vue.use(preview);
3、处理接口返回的 HTML 字符串,img 追加 preview 属性
在vue组件里,调用看大图功能,img 追加 preview 属性就可以直接生效
handleHtml(rich) {
// 使用正则表达式匹配所有图片
const reg = RegExp(/<[img]+\s+(.*?)(?<id>\w*?)[\s'"](.*?)>/g);
const match = rich.match(reg);
if (match) {
// 循环图片数组
for (let i = 0; i < match.length; i++) {
const item = match[i];
const len = item.length;
const _str = item.slice(0, len - 2) + " preview=\"0\"/>";// 追加 preview 之后的img
rich = rich.replace(item, _str);
}
}
console.log("处理之后", rich);
return rich;
}
4、处理好数据后,刷新
this.$previewRefresh();
完整源码
<!--
- Copyright © 2020-present LiuDanYang. All rights Reserved.
-->
<template>
<div class="rich-box">
<div class="rich-text" v-html="content" />
</div>
</template>
<script>
import { mapGetters } from "vuex";
import { lCatSearchTicket } from "@/api/user";
export default {
name: "TermContent",
components: {},
mixins: [],
props: {},
data() {
return {
content: "暂无内容",
params: this.$route.params
};
},
computed: {
...mapGetters(["fid"])
},
watch: {},
created() {
this.loadData();
},
mounted() {
},
destroyed() {
},
methods: {
loadData() {
lCatSearchTicket({
fair_id: this.fid,
termid: this.params.termid
}).then(res => {
if (res.status && res.data) {
console.log("处理之前", res.data.content);
this.content = this.handleHtml(res.data.content);
this.$previewRefresh();
}
});
},
handleHtml(rich) {
// 使用正则表达式匹配所有图片
const reg = RegExp(/<[img]+\s+(.*?)(?<id>\w*?)[\s'"](.*?)>/g);
const match = rich.match(reg);
if (match) {
// 循环图片数组
for (let i = 0; i < match.length; i++) {
const item = match[i];
const len = item.length;
const _str = item.slice(0, len - 2) + " preview=\"0\"/>";// 追加 preview 之后的img
rich = rich.replace(item, _str);
}
}
console.log("处理之后", rich);
return rich;
}
}
};
</script>
注意:lCatSearchTicket 为封装的接口
<img src="xxx.jpg" large="xxx_3x.jpg" preview="2" preview-text="缩略图与大图模式">
如果具备缩略图,则用 large 参数引入,如果预览图片的时候需要一些文字说明,可以给 img 再加上 preview-text 参数