如何在Vue JS中暂时禁用有条件渲染的按钮?

时间:2018-03-23 15:25:52

标签: javascript vue.js vuejs2

我有2组有条件渲染的按钮。

广告系列投放时 enter image description here

当广告系列未投放时 enter image description here

我想要做的是在广告系列暂停5秒后停用播放按钮。

这是我的标记:

<div class='m1 '>

  <md-button v-on:click='changeCampaignStatus(campaign.id, "Paused")' v-if='campaign.state==="Running"' class='md-icon-button md-accent md-raised' id='run-button'>
    <md-icon>pause</md-icon>
  </md-button>

  <md-button v-on:click='changeCampaignStatus(campaign.id, "Running")' v-if='campaign.state==="Paused"' class='md-icon-button md-accent md-raised' id='run-button'>
    <md-icon>play_arrow</md-icon>
  </md-button>

  <md-button v-on:click='changeCampaignStatus(campaign.id, "Canceled")' v-if='campaign.state==="Paused"' class='md-icon-button md-accent md-raised' id='run-button'>
    <md-icon>stop</md-icon>
  </md-button>

  <md-button v-on:click='deleteCampaign(campaign.id)' v-if='campaign.state==="Canceled"' class='md-icon-button md-accent md-raised' id='run-button'>
    <md-icon>delete_forever</md-icon>
  </md-button>

  <md-button v-on:click='duplicateCampaign(campaign.id)' class='md-icon-button md-accent md-raised'>
    <md-icon>content_copy</md-icon>
  </md-button>

  <md-button v-on:click='goToEdit'  v-if='campaign.state==="Paused"' class='md-icon-button md-accent md-raised'>
    <md-icon>mode_edit</md-icon>
  </md-button>
  <div>
    <md-chip v-for='tag in campaign.tags' :key='tag' class='mr1'>{{tag}}</md-chip>
  </div>
</div>

我不确定哪些按钮应该有id='run-button',我相信条件渲染会让以下setTimeout表现得很奇怪:

  document.getElementById("run-button").disabled = false;
  setTimeout(function(){document.getElementById("run-button").disabled = true;},5000);

有了这个逻辑,我可以让按钮最初启用并在5秒后被禁用,但如果我切换布尔值(第一行true,第二行false),它就会以某种方式混淆一切。为什么会这样?

如何正确实现?

1 个答案:

答案 0 :(得分:4)

不要混合使用Vue和直接操作DOM。

这里的最佳解决方案是创建一个属性,告诉它是否已暂停超过5秒,并将此属性添加到:disabled

例如,

data() {
  return {
    // ...
    pausedFor5Seconds: false,
    // ...
  };
},
// ...
methods: {
  // ...
  pause() {
    // some mutation that sets campaign.state to "Paused"
    this.pausedFor5Seconds = false;
    setTimeout(() => this.pausedFor5Seconds = true, 5000);
  },
  play() {
    // some mutation that sets campaign.state to "Running"
    this.pausedFor5Seconds = false;
  }
}

正如评论所说,pauseplay正在改变campaign.state的方法。

在您的模板中添加:disabled="pausedFor5Seconds"

<md-button v-on:click='changeCampaignStatus(campaign.id, "Running")'
  v-if='campaign.state==="Paused"' class='md-icon-button md-accent md-raised'
  :disabled="pausedFor5Seconds">
    <md-icon>play_arrow</md-icon>
</md-button>

id甚至不再需要(顺便提一下,你有多个具有相同run-button ID的元素 - 这些HTML无效并且弄乱了你的{{ 1}} S)。