在vue中修改编辑器html内容的图片样式(ueditor)

公司的需求是实现类似淘宝商品详情(通过图片拼接,大家都很清楚,淘宝详情一般都是采用多张图进行拼接)

文字的描述大家可能会觉得很枯燥无味,觉得代码才是最好的老师
作者将会详细地去讲解代码,在代码中找到自己的灵感!使用js实现也差不多是如此的套路。

<!-- 此页面是单页面 -->
<!--作者将会详细地去讲解代码,在代码中找到自己的灵感!-->
<template>
    <div>
         <!-- 通过设置ref获取dom,在v-html属性中就是我们展示的内容>
        <div ref="desc" class="content" v-show="showDesc" v-html="configImgDesc">
        </div>
    </div>
</template>

<script>
  import { LoadingPlugin } from 'vux'
  import axios from 'axios'

  export default {
    data () {
      return {
        showDesc: false,
        configImgDesc: ''
      }
    },
    computed: {
    },
    components: {
      LoadingPlugin
    },
    mounted () {
      this.fetch() //初始化
    },
    methods: {
      fetch () {
        // 显示
        this.$vux.loading.show() //使用了vux的loading插件
        let params = {
          ..... //这里是接口的请求参数
        }
        axios.get('你的借口地址', {params}).then(res => {
          this.configImgDesc = res.data.desc //desc是接口请求成功返回的编辑器内容
          this.showDesc = true
          let _this = this
          // 这里需要使用到nextTick,为什么使用它呢?在代码外问题(1)再说明
          _this.$nextTick(() => {
            let childrenList = _this.$refs.desc.children //获取到dom.children
            for (let i in childrenList) {
              let child = childrenList[i].children
              if (child) {
                for (let i in child) {
                  if (child[i].nodeName == 'IMG') { // 判断如果编辑器的html内如果有图片内容的时候,进行图片适配操作
                    let img = child[i]
                    img.style.width = '100%' // 自适应操作 ,让图片适应当前手机样式
                    img.style.height = 'auto' // 自适应操作
                    img.style.float = 'left' //使用式样left让图片和上一张图之间不会有间隔
                  }
                }
              }
            }
          })
          this.$vux.loading.hide()
        }).catch(res => {
          this.$vux.loading.hide()
          console.warn(res)
        })
      }
    }
  }
</script>

<style lang="less" scoped>
    html,body{
        height:100%;
        width:100%;
        padding:0;
        margin:0;
    }
    .content{
        /*font-size:0;*/ 如果你的需求是去除编辑器文字,只保留图片,请开启此样式
        width:100%;
        height:100%;
        margin-top: 0;
        padding:0;
    }
</style>

问题总结

问题(1):为什么在mouted使用了nextTick

就是在mounted(){}钩子里面使用this.$refs.xxx,我们知道在created钩子里如果我们使用ref是必须使用nextTick去获取dom的,但是在mouted中DOM结构不是已经渲染出来了吗?其实如果在DOM结构中的某个DOM节点使用了v-if、v-show或者v-for(即根据获得的后台数据来动态操作DOM,即响应式),那么这些DOM是不会再mounted阶段找到的,所以这时候我们应该机智的使用nextTick去完成接下来的操作.

猜你喜欢

转载自blog.csdn.net/qq_27295403/article/details/85089683