锚点、站点、文本问题处理

<template>
  <div class="base-info" v-html="compiledMarkdown"></div>
</template>

<script>
import marked from 'marked'
export default {
  props: {
    activeItem: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      readmeInfo: '',
      compiledMarkdown: '',
    }
  },
  computed: {
    id() {
      return this.$route.query.template
    },
    version() {
      return this.$route.query.version
    },
  },
  watch: {
    activeItem: {
      handler: function(newValue) {
        this.readmeInfo = newValue.readmeInfo || ''
        var rendererMD = new marked.Renderer()
        marked.setOptions({
          renderer: rendererMD,
          gfm: true,
          tables: true,
          breaks: true,
          pedantic: false,
          sanitize: false,
          smartLists: true,
          smartypants: false,
        })
        this.compiledMarkdown = marked(this.readmeInfo, {sanitize: true})
        if (this.readmeInfo) {
          this.$nextTick(() => {
            this.dealLink()
          })
        }
      },
      immediate: true,
      deep: true,
    },
  },
  methods: {
    dealLink() {        //处理a标签情况,1、跳转到别的站点  2、当前页面锚点   3、不是站点又不是锚点,处理成文本形式
      let element = document.querySelectorAll('a')
      element.forEach((item, index) => {
        const href = item.getAttribute('href'),    //获取标签的href属性
          isInclude = href.includes('http'),      
          isHash = item.hash,
          noClick = !isInclude && !isHash         //特殊情况,不是站点又不是锚点的处理情况
        if (noClick) {
          item.style.color = 'rgba(0, 0, 0, 0.65)'
        }
        element[index].addEventListener('click', e => {
          this.stopDefault(e)
          if (noClick) {
            return false
          }
          if (isInclude) {
            window.open(href, '_blank')
          } else {
            this.anchorScroll(href)
          }
        })
      })
    },
    stopDefault(e) {
      if (e && e.preventDefault) {
        e.preventDefault()
      } else {
        window.event.returnValue = false
      }
    },
    anchorScroll(anchorName) {
      document.querySelector(anchorName).scrollIntoView(true)    //当hash值和锚点冲突之后,手动拿到锚点的位置进行滑动
    },
  },
}
</script>
<style lang="less" scoped>
.base-info {
  padding: 10px 24px;

  /deep/ * {
    white-space: normal;
  }
}
</style>
原文地址:https://www.cnblogs.com/MJmajong/p/13522536.html