我在组件中定义了自定义指令“focus”:
<script>
export default {
name: 'demo',
data () {
return {
show: true
}
},
methods: {
showInput () {
this.show = false
}
},
directives: {
focus: {
inserted: function (el) {
el.focus()
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的 html 模板:
<template>
<div>
<input type="number" id="readonly" v-if="show">
<button type="button" @click="showInput" v-if="show">show</button>
<input type="number" id="timing" v-model="timing" v-if="!show" v-focus>
</div>
</template>
Run Code Online (Sandbox Code Playgroud)
但是当我点击 时button,input#timing不能自动对焦。
当我把input#readonly和button成div,只使用一个V-如果,input#timing可以自动对焦 …