LoginSignup
3
2

More than 3 years have passed since last update.

Vuetifyのテキストエリア(v-textarea)内のカーソル位置に文字列を挿入する

Last updated at Posted at 2020-04-07

はじめに

テキストエリア内の文字列に、何か別の文字列を挿入したいという場合がある。

例えば、お客様に送信する定形メールでは、お客様の名前は、%name%などとして送信時に置換する。

この定型文を作成している場合に、置換文字一覧表でクリックしたら、自動的に定形メールが入力されているテキストエリアに挿入したい。

Javascriptでの実現方法

Javascriptでは、以下のようにします。まとめていただいてありがとうございます。

Vuetifyのv-textareaで実現する

Vuetifyは、色々とコンポーネント化がされています。v-textareaですとどう実現するのか?

結論からいうと、以下になります。

  1. v-textarearefで参照するようにします。
  2. this.$refs.textarea.$refs.inputが実際のtextareaタグを参照する。
  3. execCommandで挿入する
<template>
<div id="app">
  <v-app id="inspire">
    <v-container fluid>
      <v-textarea
        ref="textarea"
        label="TextArea"
      ></v-textarea>
   <v-btn @click="execInsertText">Insert</v-btn>
  </v-app>
</div>
</template>

<script>
export default {
  data: () => ({
    insertText: '%insertChar%'
  }),
  methods: {
    execInsertText() {
      const textarea = this.$refs.textarea.$refs.input
      textarea.focus()
      document.execCommand('insertText', false, this.insertText)
    }
  }
}
</script>

デモ

2020-04-08_07h42_02.gif

See the Pen Insert character at Cursor position in Vuetify Textarea2 by Shigehiro IDANI (@1da2) on CodePen.

execCommandを使わない方法のデモ

こちらは、execCommandを使わない方法で実現しています。また、挿入後にフォーカス位置を挿入した文字の後に来るように調整をしています。

See the Pen Insert character at Cursor position in Vuetify Textarea by Shigehiro IDANI (@1da2) on CodePen.

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2