【问题标题】:Custom directive v-focus on input with v-show in Vue app在 Vue 应用程序中使用 v-show 自定义指令 v-focus 输入
【发布时间】:2018-04-11 04:37:47
【问题描述】:

我注册了一个用于聚焦输入的自定义指令。我使用来自Vue docs的代码:

// Register a global custom directive called v-focus
Vue.directive('focus', {
  // When the bound element is inserted into the DOM...
  inserted: function (el) {
    // Focus the element
    el.focus()
  }
})

我在这些元素上应用v-focus

<input v-show="isInputActive" v-focus>

<div v-show="isDivActive">
  <input v-focus>
</div>

但它不起作用。只有当我用v-if 替换v-show 时它才有效,但我必须使用v-show。有解决办法吗?

【问题讨论】:

  • 每次v-show 指令中的条件被赋值为true 时,您的元素都不会重新渲染。有关更多信息,请参阅此处的文档:vuejs.org/v2/guide/conditional.html#v-if-vs-v-show
  • 我知道,事实上我在问如何使用 v-focus 和 v-show
  • 它是否适用于v-if?然后它应该重新渲染...
  • 用 v-if 可以,但我需要使用 v-show

标签: javascript vue.js vuejs2


【解决方案1】:

你可以给v-focus传一个值,然后添加一个更新钩子函数:

Vue.directive("focus", {
  inserted: function(el) {
    // Focus the element
    el.focus()
  },
  update: function(el, binding) {
    var value = binding.value;
    if (value) {
      Vue.nextTick(function() {
        el.focus();
      });
    }
  }
})

var app = new Vue({
  el: "#app",
  data: function() {
    return {
      ifShow: true
    }
  },
})
<script src="https://unpkg.com/vue@2.5.2/dist/vue.js"></script>

<div id="app">

  <input type="text" v-focus="ifShow" v-show="ifShow">
  <br>
  <button @click="ifShow = !ifShow">toggle</button>
</div>

【讨论】:

    【解决方案2】:

    我认为更好的解决方案应该是当isInputActiveisDivActive 发生变化时你可以focus

    <input v-show="isInputActive" v-ref="input">
    
    watch: {
      isInputChange(value) {
        if (value) this.$refs.input.focus()
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2021-04-23
      • 2020-01-27
      • 2015-10-29
      • 2020-02-18
      • 1970-01-01
      • 2020-12-20
      • 1970-01-01
      • 2019-05-22
      • 2019-06-07
      相关资源
      最近更新 更多