vue自定义指令如何通过动态的传递参数来控制DOM显示

小围巾儿
  • 20

写了一个全局loading 自定义指令,调用的时候显示loading和“加载中”的提示,如图
image.png

现在 “加载中” 是写死的,怎样在调用的地方动态传入别的提示呢,比如 “正在跳转”

代码如下:
loading.vue

<template>
  <div
    v-show="visible"
    class="loading-wrap"
  >
    <div class="loading-box">
      <div class="img-box">
        <img
          src="./images/loading.gif"
          alt=""
        >
      </div>
      <p>加载中...</p>
    </div>
  </div>
</template>

<script type="text/ecmascript-6">
export default {
  components: {},
  data() {
    return {
      visible: false
    }
  }
}
</script>

<style lang="stylus" scoped>
.loading-wrap
  position absolute
  left 0
  right 0
  top 0
  bottom 0
  background rgba(0, 0, 0, 0.2)
.loading-box
  position absolute
  left 50%
  top 50%
  // height 60px
  width 60px
  transform translate(-50%, -50%)
  text-align center
  .img-box
    width 100%
    height 60px
    >img
      width 60px
  >p
    margin-top 5px
    color $white-color
    letter-spacing 1px
</style>

loading.js

import Vue from 'vue'
import Loading from './loading.vue'

const Mask = Vue.extend(Loading)

const toggleLoading = (el, binding) => {
  if (binding.value) {
    Vue.nextTick(() => {
      // 控制Loading组件显示
      el.instance.visible = true
      // 插入到目标元素
      insertDom(el, el, binding)
    })
  } else {
    el.instance.visible = false
  }
}

const insertDom = (parent, el) => {
  parent.appendChild(el.mask)
}

export default {
  bind(el, binding, vnode) {
    const mask = new Mask({
      el: document.createElement('div'),
      data() {}
    })
    el.instance = mask
    el.mask = mask.$el
    el.maskStyle = {}
    binding.value && toggleLoading(el, binding)
  },
  update(el, binding) {
    if (binding.oldValue !== binding.value) {
      toggleLoading(el, binding)
    }
  },
  unbind(el, binding) {
    el.instance && el.instance.$destroy()
  }
}

App.vue

<template>
  <div
    id="app"
    v-loading="loading"
  >
    <router-view />
  </div>
</template>

<script>
import {mapState} from 'vuex'
export default {
  name: 'App',
  computed: {
    ...mapState('examine', ['loading'])
  }
}
</script>

<style lang="stylus">
// @import "./style/index.styl"

#app
  position fixed
  top 0
  bottom 0
  font-family 'Avenir', Helvetica, Arial, sans-serif
  -webkit-font-smoothing antialiased
  -moz-osx-font-smoothing grayscale
  font-size 14px
  letter-spacing 0.05em
  width 100%
  height 100%
  overflow hidden
</style>
评论
阅读 148
1 个回答

给你举个例子,下面是elementUI的loading使用:

<div
    v-loading="loading"
    element-loading-text="拼命加载中"
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
>
    
</div>

在你的loading.js文件中bindupdate中都有el参数;
然后el.getAttribute方法;这么说你有思路了吗

撰写回答

登录后参与交流、获取后续更新提醒

宣传栏