directive用法

496 阅读1分钟

一、编写布局

<div v-loading="isLoading">{{data}}</div>
<input type="button" @click="update" value="更新">

二、逻辑分析

点击更新按钮,触发自定义指令isLoading,弹出一个加载中的div,三秒以后删除div

三、逻辑编写

import Vue from 'vue'
export default {
  name: 'HelloWorld',
  data () {
    return {
      isLoading:false,
      data:''
    }
  },
  methods:{
    update(){
      this.isLoading = true;
      setTimeout(()=>{
          this.data = '用户数据';
          this.isLoading = false;
      },3000)
    }
  }
}

Vue.directive('loading',{
    update(el,binding,vnode){
       if(binding.value){
            const div = document.createElement('div');
            div.innerText ='加载中...'
            div.setAttribute('id','loading')
            div.style.position = "fixed";
            div.style.left = 0;
            div.style.top = 0;
            div.style.width = '100%'
            div.style.height = '100%'
            div.style.display = 'flex'
            div.style.justifyContent = 'center'
            div.style.alignItems = 'center' 
            div.style.color = 'white'
            div.style.background = 'rgba(0,0,0,.7)'
            document.body.append(div)
    }else{
       document.body.removeChild(document.getElementById('loading'));
    }
 }
})

四、效果展示

五、简单实现思路

<div :style="visible">加载中...</div>
 ----------------------------------
 visible:"visibility:hidden"
 ----------------------------------
this.visible = "visibility:visible"
  setTimeout(()=>{
     this.data = '用户数据';
    this.visible = "visibility:hidden"
  },3000)
  
  表面上看很方便,但是每次写都要写一个div来实现,解决思路应该是动态创建,并且封装一个vue插件,然后import来实现。

如何封装请看下面的章节。