【问题标题】:Implementing a v-loading directive, where content is replaced while data is loading实现 v-loading 指令,在加载数据时替换内容
【发布时间】:2019-01-08 05:45:31
【问题描述】:

我正在尝试在 Vue 中实现 v-loading 指令,其中元素的内容被一个微调器替换,而表达式的计算结果为 true。

它会这样使用:

<div v-loading="loading">
  <p v-if="!data"> No data </p>
  <p v-else>Here is the data: {{data}}</p>
</div>

这是我的实现(打字稿):

import Vue from 'vue';

Vue.directive('loading', {
  bind(el: HTMLElement, binding: any, vnode: any) {
    console.log(vnode);
    // console.log(this, arguments);
    vnode.data.html = el.innerHTML;
    vnode.data.loading = binding.value;

    if (binding.value) {
      el.innerHTML = `<i class='fa fa-spin fa-spinner'></i>`;
    } else {
      el.innerHTML = vnode.data.html;
    }
  },

  update(el: HTMLElement, binding: any, vnode: any, oldVnode: any) {
    console.log(el.innerHTML);
    // console.log("update", this, arguments);

    if (binding.value) {
      el.innerHTML = `<i class='fa fa-spin fa-spinner'></i>`;
    } else {
      el.innerHTML = oldVnode.data.html;
    }

    vnode.data.html = oldVnode.data.html;
    vnode.data.loading = binding.value;
  }
});

它有点工作,但呈现的 html 是元素创建时的 html。所有的动态渲染都丢失了。

代替指令,我可以创建一个v-loading 组件:

<template>
  <div>
    <slot v-if="!loading"></slot>
    <i v-else class="fa fa-spin fa-spinner"></i>
  </div>
</template>

但我宁愿有指令。不幸的是,我对vue框架和vnodes的了解还不够,vnodes上API中的doc重定向到here,信息不多。

有什么想法吗?

【问题讨论】:

    标签: typescript vuejs2 directive


    【解决方案1】:

    检查Vue instance Life cycle,您的指令破坏了el,因此除非re-mount(再次编译模板),否则它不会正确呈现。

    以下是两种解决方案:

    解决方案 1:您可以附加一个元素来显示微调器,然后隐藏其其他子项。

    Vue.config.productionTip = false
    let vMyDirective = {}
    vMyDirective.install = function install (_Vue) {
      let _uid = 'vue-directive-loading' + Date.now().toString('16')
      _Vue.directive('loading', {
        inserted: function (el, binding) {
          let spinner = document.createElement('span')
          spinner.id = _uid
          spinner.innerHTML = 'Loading...'
          spinner.style.display = binding.value ? 'block' : 'none'
          spinner.style['background-color'] = 'red'
          spinner.left = 0
          spinner.top = 0
          spinner.style.position = 'absolute'
          el.childNodes.forEach((item) => {
            item.style.display = binding.value ? 'none' : ''
          })
          el.appendChild(spinner)
        },
        update: function (el, binding, vnode) {
          let spinner = document.getElementById(_uid)
          spinner.style.display = binding.value ? 'block' : 'none'
          el.childNodes.forEach((item) => {
            if(item.id === _uid) return
            item.style.display = binding.value ? 'none' : ''
          })
        }
      })
    }
    
    Vue.use(vMyDirective)
    
    new Vue({
      el: '#app',
      data() {
        return {
          loading: true,
          dataset: ''
        }
      },
      methods:{
        toggleLoading: function() {
          this.loading = !this.loading
        },
        AddData: function () {
          this.dataset = this.dataset + 'a'
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
    <div id="app">
      <button v-on:click="toggleLoading()">Toggle Loading {{loading}}</button>
      <button v-on:click="AddData()">Add Data</button>
      <div v-loading="loading">
        <p v-if="!dataset"> No data </p>
        <p v-else>Here is the data: {{dataset}}</p>
      </div>
    </div>

    解决方案 2:在 loading === false 时强制更新(并强制使用新的 vnode.key 重新挂载),但这可能不是一种好方法,因为存在针对 modifying vnode 的警告。。 p>

    Vue.config.productionTip = false
    let vMyDirective = {}
    vMyDirective.install = function install (_Vue) {
      _Vue.directive('loading', {
        bind: function (el, binding, vnode) {
          if(binding.value) {
            el.innerHTML = '<span style="background-color:red;top:0;left;0">loading...</span>'
          }
        },
        update: function (el, binding, vnode) {
          if(binding.value) {
            el.innerHTML = '<span style="background-color:red;top:0;left;0">loading...</span>'
          } else {
            vnode.key += '1'
            vnode.context.$forceUpdate()
          }
        }
      })
    }
    
    Vue.use(vMyDirective)
    
    new Vue({
      el: '#app',
      data() {
        return {
          loading: true,
          dataset: ''
        }
      },
      methods:{
        toggleLoading: function() {
          this.loading = !this.loading
        },
        AddData: function () {
          this.dataset = this.dataset + 'a'
        }
      }
    })
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>
    <div id="app">
      <button v-on:click="toggleLoading()">Toggle Loading {{loading}}</button>
      <button v-on:click="AddData()">Add Data</button>
      <div v-loading="loading">
        <p v-if="!dataset"> No data </p>
        <p v-else>Here is the data: {{dataset}}</p>
      </div>
    </div>

    【讨论】:

    • 非常感谢您的完整回答!只是一个问题:为什么要更改 vnode.key,反对修改 vnode 的警告在哪里?
    • @coyotte508 当密钥改变时(Vue Guide: list ->keyhow to remount),Vue 会重新挂载它。然后对于第二个问题,检查Vue Guide: custom directiveApart from el, you should treat these arguments as read-only and never modify them. If you need to share information across hooks, it is recommended to do so through element’s dataset.
    • @coyotte508 你可以在 hook='update' 和 'bind' 中添加console.log('something'),你会发现一旦在 hook='update' 中更改了 key,它会再次绑定。如果注释掉vnode.key += '1',只会触发hook='update'。
    猜你喜欢
    • 2017-11-29
    • 2012-06-26
    • 2014-08-05
    • 1970-01-01
    • 2023-03-29
    • 2015-04-28
    • 1970-01-01
    • 2013-12-18
    • 1970-01-01
    相关资源
    最近更新 更多