javascript - 自定义指令 v-focus 在 Vue 应用程序中使用 v-show 输入

标签 javascript vue.js vuejs2

我注册了一个用于聚焦输入的自定义指令。我使用来自 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-show 替换为 v-if 时它才有效,但我必须使用 v-show。有解决办法吗?

最佳答案

可以给v-focus传一个值,然后添加一个update hook函数:

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>

关于javascript - 自定义指令 v-focus 在 Vue 应用程序中使用 v-show 输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47011188/

相关文章:

javascript - 单击内部标签时将类添加到 li

javascript - 合并两个具有共同元素的 JSON 对象

javascript - 使用由于组件问题而无法正常工作的事件使用 Vue.js 上传图像

vue.js - VueJS 基于角色的路由器身份验证

html - Vuetify <v-data-table> 自定义 <th> header

javascript - 如何使用 node.js 从蓝牙设备接收数据

javascript - 在node.js中使用xpath和xmldom替换部分xml

javascript - Vue图像src文件路径不起作用

vue.js - 使用SSR时如何防止Nuxt水化?

javascript - Vuex 状态数组键