【问题标题】:Focus state remains after DOM element is updated更新 DOM 元素后焦点状态保持不变
【发布时间】:2021-10-30 02:14:58
【问题描述】:

我正在使用Vue + Bulma

按钮单击事件用于更新 DOM。但是,在 DOM 更新后,焦点状态仍然应用于按钮。

我希望更新后的按钮没有焦点状态。

解决这个问题的最佳方法是什么?是否有更惯用的 Vue.js 方式来处理这种常见情况?

下面的简化示例:

var app = new Vue({
  el: '#app',
  data: {
    options: [{
      text: "This is the first text"
    }, {
      text: "This is the second text"
    }, {
      text: "This is the third text"
    }],

    index: 0,
  },

  methods: {
    nextText: function() {
      if (this.index < this.options.length - 1) {
        this.index++;
      } else {
        this.index = 0;
      }
    }
  }
})
<link href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div id="app">
  <button v-on:click="nextText()" class="button is-primary is-outlined">{{ options[index].text }}</button>
</div>

【问题讨论】:

  • 但是你仍然悬停在元素上,不是吗?我怀疑您是否设法在更改按钮文本所需的几毫秒内将鼠标光标从元素上移开...
  • @CBroe 运行代码 sn-p。即使鼠标离开按钮,它仍保持悬停状态。
  • 这不是 hover 状态,而是 focus - 按钮接收到的状态是因为您正在点击它。
  • @CBroe 知道如何在移动设备上处理这个问题吗?我在下面的答案在桌面上修复了,但我在移动设备上仍然遇到同样的问题

标签: javascript css vue.js bulma


【解决方案1】:

我通过强制 Vue 重新渲染按钮元素解决了这个问题。

这在我的上下文中是有道理的,因为我希望按钮表现得像一个新按钮,而不是应用任何以前的“焦点”。

这可以通过在按钮上设置 :key 属性来实现。

 <button v-on:click="nextText()" :key="index" class="button is-primary is-outlined">{{ options[index].text }}</button>

以下更新代码。

var app = new Vue({
  el: '#app',
  data: {
    options: [{
      text: "This is the first text"
    }, {
      text: "This is the second text"
    }, {
      text: "This is the third text"
    }],

    index: 0,
  },

  methods: {
    nextText: function() {
      if (this.index < this.options.length - 1) {
        this.index++;
      } else {
        this.index = 0;
      }
    }
  }
})
<link href="https://cdn.jsdelivr.net/npm/bulma@0.9.3/css/bulma.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.16/vue.js"></script>

<div id="app">
  <button v-on:click="nextText()" :key="index" class="button is-primary is-outlined">{{ options[index].text }}</button>
</div>

【讨论】:

    猜你喜欢
    • 2016-10-19
    • 1970-01-01
    • 2016-11-01
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-15
    相关资源
    最近更新 更多