In the Vue project, how to modify the text in the tag after implementing the HTML tag

Vue.js is a popular open-source JavaScript framework that helps developers build user interfaces more easily. In Vue.js, we can use directives to bind events and respond to user interaction.

This article will explain how to modify the text in the tag after the user double-clicks a span tag in the Vue.js project.

In Vue.js, the above functions can be realized through the following steps:

  1. In the template, add a double-click event listener (v-on:dblclick) and a focus-lost event listener (v-on:blur) to the span tag, and use the v-model directive to bind the compound variable text:
    <template>
      <span v-on:dblclick="updateText()" v-on:blur="saveText()" v-model="text"></span>
    </template>
    

  2. Use Vue3 and <script setup>syntax sugar to define the initial value of the responsive data text and the updateText and saveText methods respectively.

  3. In the updateText method, make the span tag editable and give it focus. In this way, when the user double-clicks the span tag, the text can be edited directly on the page.

  4. In the saveText method, save the text edited by the user to the data of the Vue instance, and make the span tag return to an uneditable state.

    <script setup>
    import { ref } from 'vue'
    
    const text = ref('双击我进行修改')
    
    function updateText() {
      // 让span标签变成可编辑状态
      event.target.contentEditable = true;
      // 设置焦点到span标签
      event.target.focus();
    }
    
    function saveText() {
      // 将用户编辑后的文本保存到text中
      text.value = event.target.innerText;
      // 让span标签变回不可编辑状态
      event.target.contentEditable = false;
    }
    </script>
    
    <template>
      <span v-on:dblclick="updateText()" v-on:blur="saveText()" v-model="text"></span>
    </template>
    

The above is how to modify the text in the tag after the user double-clicks a span tag in the Vue.js project. Hope to help you! 

おすすめ

転載: blog.csdn.net/weixin_42117463/article/details/129848103