I registered a custom directive for focusing input. I use the code from 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()
}
})
And the I apply v-focus
on these elements:
<input v-show="isInputActive" v-focus>
<div v-show="isDivActive">
<input v-focus>
</div>
but it doesn't work. It works only if I replace v-show
with v-if
but I have to use v-show
. Is there a solution?
I registered a custom directive for focusing input. I use the code from 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()
}
})
And the I apply v-focus
on these elements:
<input v-show="isInputActive" v-focus>
<div v-show="isDivActive">
<input v-focus>
</div>
but it doesn't work. It works only if I replace v-show
with v-if
but I have to use v-show
. Is there a solution?
-
Your element isn't re-rendered each time the condition inside the
v-show
directive is valued astrue
. See the documentation here for more information : vuejs/v2/guide/conditional.html#v-if-vs-v-show – Thomas Ferro Commented Oct 30, 2017 at 9:07 - I knew that, infact I'm asking how to use v-focus with v-show – Fred K Commented Oct 30, 2017 at 9:17
-
Does it work with
v-if
? It should re-render then... – sandrooco Commented Oct 30, 2017 at 9:22 - With v-if it works but I need to use the v-show – Fred K Commented Oct 30, 2017 at 9:26
2 Answers
Reset to default 4You can pass a value to v-focus, then add a update hook function:
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./[email protected]/dist/vue.js"></script>
<div id="app">
<input type="text" v-focus="ifShow" v-show="ifShow">
<br>
<button @click="ifShow = !ifShow">toggle</button>
</div>
I think the better solution should be you can focus
when isInputActive
or isDivActive
change.
<input v-show="isInputActive" v-ref="input">
watch: {
isInputChange(value) {
if (value) this.$refs.input.focus()
}
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744225044a4563963.html
评论列表(0条)