iview input实现默认获取焦点并选中文字


1. 业务背景

配置页面,可新建和复制任务;当复制任务的时候,要把名字的input框默认获取焦点,并全选任务名。效果如下:

2. 代码实现

<template>
    <Form :model="config">
      <FormItem label="任务名称">
        <Input
          ref="taskNameInput"
          id="taskNameInput"
          placeholder="请输入任务名称"
          v-model.trim="config.taskName"
        />
      </FormItem>
      ···
    </Form>
</template>

<script>
export default {
  name: "Config",
  computed: {
    taskName() {
      return this.$route.query.taskName;
    }
  },
  data() {
    return {
      config: {
        taskName: "",
        ···
      }
    };
  },
  methods: {
    async getTaskConfig() {
      // 接口获取数据
    },
    setNameFocus() {
      this.$refs.taskNameInput.focus();
      document.querySelector("#taskNameInput .ivu-input").select();
    }
  },
  async mounted() {
    if (this.taskName) {
      await this.getTaskConfig();
      this.setNameFocus();
    }
  }
};
</script>

说明: 因为iview的Input并没有提供选中的方法,所以这时候只能使用原生的select()方法进行选中;调用该方法的dom是原生的input,而不是iview的i-input


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM