Vue指令运用

 Vue指令运用(数据加载Loading功能、降低对代码的侵入性)

<html>
<head>
  <meta charset="utf-8"/>
  <title>Vue指令</title>
</head>
<style>
  .bgpink{
    background-color: pink;
    width:150px;
  }
  .f{display: flex;}
  .xc{justify-content: center;}
  .ac{align-items: center;}
</style>
<body>
  <div id="root" v-loading="isLoading">
    <div>{{data}}</div>
    <div class='bgpink f ac xc' @click="update">点击更新</div>
  </div>
</body>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
  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'))
      }
    }
  })
  var vm = new Vue({
    el: '#root',
    data(){
      return {
        data:'asd',
        isLoading: false,
        message: '123123'
      }
    },
    created(){
      this.$on('my_events', val => {
        this.message = '-----'
      })
    },
    methods:{
      handleClick(){
        this.$emit('my_events')
      },
      update(){
        this.isLoading = true
        setTimeout(()=>{
          this.isLoading = false
        }, 1000)
      }
    }
  })
</script>
</body>
</html>

 

 

posted @ 2021-01-19 21:16  进心进利  阅读(91)  评论(0编辑  收藏  举报