source

Vue 앱에서 v-show를 사용한 입력에 대한 사용자 지정 지시 v-focus

goodcode 2022. 7. 31. 22:58
반응형

Vue 앱에서 v-show를 사용한 입력에 대한 사용자 지정 지시 v-focus

입력에 초점을 맞추는 커스텀 디렉티브를 등록했습니다.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에 값을 전달한 다음 업데이트 후크 함수를 추가할 수 있습니다.

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>

더 나은 해결책은 당신이 할 수 있는 것입니다.focus언제isInputActive또는isDivActive바꾸다.

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

watch: {
  isInputChange(value) {
    if (value) this.$refs.input.focus()
  }
}

언급URL : https://stackoverflow.com/questions/47011188/custom-directive-v-focus-on-input-with-v-show-in-vue-app

반응형