美文网首页Vuevue
Vue移动端可放大缩小图片vue-photo-preview

Vue移动端可放大缩小图片vue-photo-preview

作者: Lia代码猪崽 | 来源:发表于2020-04-28 17:21 被阅读0次

效果

与本文无关样式已马赛克

点击图片后:


可通过手指来放大缩小查看图片

使用插件

vue-photo-preview

一、安装

npm install vue-photo-preview --save

二、引用

view.vue中的<script></script>中引用:

<script>
import Vue from "vue";
import preview from "vue-photo-preview";
import "vue-photo-preview/dist/skin.css";
Vue.use(preview);

export default {
  name: "view",
  // ....
}
</script>

三、给异步获取到的文章内容里的图片加上功能插件

步骤:

  1. 异步获取到文章内容
  2. 找到文章内容里的所有图片dom节点(通过ref来获取)
  3. 给图片dom节点都加上属性preview(使用序号来定义),属性preview-text(使用图片名字来定义,图片的alt属性有)
  4. 调用this.$previewRefresh();

完整代码:

<template>
  <div class="view">
    <div class="title">{{ note.title }}</div>
    <!-- 注意,一定要加上ref,后面会用到 -->
    <div class="content" ref="content">
      <div v-html="note.content"></div>
    </div>
  </div>
</template>

<script>
import Vue from "vue";
import preview from "vue-photo-preview";
import "vue-photo-preview/dist/skin.css";
Vue.use(preview);

// 引入与后台数据交互的封装后的api
import { Document_ap } from "@/api";

export default {
  name: "view",
  data() {
    return {
      note: {
        title: '',
        content: ''
      }
    }
  },
  created() {
    // 获取页面数据,写死id为1
    this.getNote(1);
  },
  methods: {
    async getNote(id) {
      const params = {
        Guid: id
      };
      const res = await Document_api.getDocumentDetail(params);
      // 如果交互成功
      if (res.data.Code === 0) {
        this.note = res.data.Result;
        // 重点来了!要写在回调函数里
        setTimeout(() => {
          // 获取到所有图片dom节点
          const imgs = this.$refs.content.getElementsByTagName("img");
          for (let i = 0; i < imgs.length; i++) {
            const img = imgs[i];
            // console.log(img)
            // 给图片加上preview、preview-text属性,例如:<img preview = "0"  preview-text= "描述文字" />
            img.setAttribute("preview", i);
            img.setAttribute("preview-text", img.getAttribute("alt"));
            this.$previewRefresh();
          }
        }, 500);
      }
  }
}
</script>

相关文章

网友评论

    本文标题:Vue移动端可放大缩小图片vue-photo-preview

    本文链接:https://www.haomeiwen.com/subject/mplbwhtx.html