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