vue在光标的位置插入内容

  • Post author:
  • Post category:vue


一,在textarea中加入id

<el-form-item :label="$t('message_template_content')" prop="content">

         <el-input

           type="textarea"

           id="textarea"

           :autosize="{ minRows: 5, maxRows: 10}"

           :placeholder="$t('common_input')"

           v-model="messageTemplate.content"

         />

       </el-form-item>

二、在methods中写入方法

async insertVariable(value) {

      const myField = document.querySelector('#textarea');

      // const myField = this.$refs.singleText;

      console.log('myField--',myField);

      if(myField.selectionStart || myField.selectionStart === 0) {

        let startPos = myField.selectionStart;

        let endPos = myField.selectionEnd;

        this.messageTemplate.content = myField.value.substring(0, startPos) + value

                    + myField.value.substring(endPos, myField.value.length);

        await this.$nextTick() // 这句是重点, 圈起来

        myField.focus();

        myField.setSelectionRange(endPos + value.length, endPos + value.length);

      } else {

        this.messageTemplate.content = value;

      }

    },