导航

Vue.directive

Posted on 2020-04-09 22:55  init01  阅读(173)  评论(0编辑  收藏  举报
<!DOCTYPE html>
<html lang="en">
  <head>
    <title></title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  </head>
  <body>
    <div id="root">
      <div v-loading="isLoading">{{data}}</div>
      <button @click="update">更新</button>
    </div>
    <script>
      debugger
       //v-loading 
      Vue.directive('loading',function update(el, binding, vnode){  //界面上元素发生更新时候调用
        console.log(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.color = 'white'
            div.style.alignItems = 'center';
            div.style.background = '#3333';
            document.body.append(div)
          }else{
            const div = document.getElementById('loading');
            div && document.body.removeChild(div)
            
          }
        }
      )

      new Vue({
        el:'#root',
        data(){
          return{
            isLoading:false,
            data:''
          }
        },
        methods:{
          update(){
            this.isLoading = true;
            setTimeout(()=>{
              this.data = "用户数据";
              this.isLoading = false
            },3000)
          }
        }
      })
    </script>
  
  </body>
</html>