1)输入框给一个v-focus属性:
<input ref="searchInput" v-focus>
2)自定义获得焦点指令:
directives: {focus: {// 指令的定义inserted: function(el) {el.focus();}}},
3)点击事件触发聚焦
this.$nextTick( () => {this.$refs.searchInput.focus();})
完整代码:
<input@keyup="searchGame"ref="searchInput"v-focusclass="game__search-input"type="text"placeholder="搜索"v-model="searchGameName"><div @click="handleKey" class="game__pop-key-search"></div><script>
export default {name: 'SelectGame',components: {},data() {return{searchGameName: '', // 搜索名称}},directives: {focus: {// 指令的定义inserted: function(el) {el.focus();}}},methods: {/*** 点击开始搜索游戏*/searchGame () {3)点击事件触发聚焦this.$nextTick( () => {this.$refs.searchInput.focus();})let gameList = this.games;if (this.searchGameName !== '') {gameList = this.games.filter((item) => {return item.app_name.indexOf(this.searchGameName) !== -1})}this.picGameData(gameList);},/*** 点击字符搜索游戏*/handleKey() {this.$nextTick( () => {this.$refs.searchInput.focus();})}}
}
vue自定义指令知识:https://cn.vuejs.org/v2/guide/custom-directive.html