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

posted @ 2019-12-06 10:47  ฅ˙-˙ฅ  阅读(872)  评论(0编辑  收藏  举报