我试图在Vue中设置输入元素的焦点.js.我在网上找到了一些帮助,但没有一个解释对我有用.

这是我的代码:

<template>
    <form method="post" action="" v-on:submit.prevent="search">
        <input type="text" placeholder="Person name" required v-model="name" v-el="nameInput" />
        <input type="text" placeholder="Company" required v-model="company" v-el="domainInput" />
        <input type="submit" value="Search" class="btn show-m" />
    </form>
</template>

<script>
export default {
    data () {
        return {
            contacts: [],
            name: null,
            company: null
        }
    },
    ready: {
        // I tried the following :
        this.$$.nameInput.focus();
        this.$els.nameInput.focus();
        // None of them worked !
    }
    methods: {
        search: function (event) {
            // ...

            // I also would like to give the focus here, once the form has been submitted.
            // And here also, this.$$ and this.$els doesn't work
        },
    }
}
</script>

我试着用this.$$.nameInput.focus();this.$els.nameInput.focus();来搜索我能在网上找到的焦点,但this.$$是未定义的,this.$els是空的.

如果这有帮助的话,我正在使用vue.JSV1.0.15

谢谢你的帮助.

推荐答案

在vue 2中.你可以用directive来解.

Vue.directive('focus', {
    inserted: function (el) {
        el.focus()
    }
})

然后可以对输入和其他元素使用v-focus属性:

<input v-focus>

Vue.js相关问答推荐

如何根据数据库中的条件在vue中创建类

为什么我在 Vue npm run serve 的 localhost 中得到无法获取

使用 nuxt.js 组件自动导入对性能不利吗?

拖入 vue2-google-map 后如何获取标记位置?

将函数作为属性传递给 Vue 组件

VueJS CKeditor5 上传图片

Axios Intercept 在第一次调用时未从 localStorage 应用令牌

为什么在 Vue.js 中使用 `var` 关键字?

用 axios 搜索:新字符时取消之前的请求

如何只查看数组中的一个对象?

Vuetify 在数据表中插入操作按钮并获取行数据

如何为 Vue 项目设置 lint-staged?

如何使用 vue-resource 添加额外的标头来发布请求?

在 vuejs 中将旧代码修改为 vue router 4

即使在客户端设置 Access-Control-Allow-Origin 或其他 Access-Control-Allow-* 标头后也出现 CORS 错误

Vue更改宽度和内容

try 通过 Vue.js 中的渲染传递props并观察它们

VueJS 路由 - 使用子路由和 Vuetify 时如何停止多个活动路由(active routes)?

Vue Router beforeRouteLeave 不会停止子组件

单击 v-select 项目时如何获取对象而不是单个值?