【问题标题】:Forcing Vue to re-render elements with removed attributes强制 Vue 重新渲染具有已移除属性的元素
【发布时间】:2020-09-09 17:41:25
【问题描述】:

在我的 Vue 项目中,我使用了一个第三方库,它没有设置为与 Vue 很好地集成,因为它执行手动 DOM 操作,例如通过删除将有条件禁用的元素的“禁用”属性。每当这个库执行这些操作时,我希望 Vue 刷新它的状态。乍一看,$forceUpdate 方法似乎很完美,但它似乎并没有像我预期的那样工作......Here's 一个演示东西的 Codepen,在调用 removeAttribute 之后,我需要一些制作 Vue 的方法再次开始应用有条件的“禁用”标签。

代码:

const vm = new Vue({
  el: "#app",
  data: {
    buttonDisabled: true,
  }
});

document.getElementById('button').removeAttribute('disabled');

vm.$forceUpdate(); // doesn't work

<div id="app">
  <button id="button" :disabled="buttonDisabled">
    test
  </button>
</div>

【问题讨论】:

    标签: javascript html vue.js dom


    【解决方案1】:

    您应该将您的模板视为“纯函数”,这意味着您不应干扰渲染的输出,否则您会因此类副作用而得到意想不到的结果。

    Vue 跳过重新渲染,因为没有发生任何变化,因此您需要进行更改以使其正确重新渲染。

    在您的具体示例中,您可以通过使用 $nextTick 切换 disabled 属性来做到这一点。

    document.getElementById('button').removeAttribute('disabled');
    
    // first change
    vm.buttonDisabled = false;
    
    // wait until the update queue is done so Vue can pick up the changes
    vm.$nextTick(() => {
      // toggle it back on
      vm.buttonDisabled = true;
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-20
      • 2017-05-08
      • 2012-01-31
      • 2017-03-09
      • 1970-01-01
      • 2020-12-16
      • 2021-07-04
      • 1970-01-01
      相关资源
      最近更新 更多