1.ref实现,要写在mounted里面
<input type="text" v-model="name" ref="getFocus" /> <script> export default { data() { return { name: '' } }, mounted() { this.$refs.getFocus.focus() } } </script>
2.使用自定义指令
Vue.directive('getFocus', { inserted: function(el, binding) { el.focus() } }) <input type="text" v-model="name" v-getFocus />
3.使用原生js
<input type="text" v-model="name" id="getFocus" /> <script> export default { data() { return { name: '' } }, mounted() { document.getElementById('getFocus').focus() } } </script>