zl程序教程

您现在的位置是:首页 >  前端

当前栏目

vue实现点击修改文字

Vue 实现 修改 点击 文字
2023-09-11 14:19:18 时间

场景

点击文字,实现用户可输入修改该文字并且鼠标点击其他元素触发保存事件

技术:
vue2.x,
UI框架使用的是ant design 1.7.8

实现效果:

点击前:在这里插入图片描述点击后:
在这里插入图片描述
点击输入框外部元素实现保存:
在这里插入图片描述

template代码块

    <div class="queryDatatitle" :title="queryData.name" @click="updateNmae(queryData.name)">
      <div v-if="!isUpdateName">{{ queryData.name }}</div>
      <div v-else>
        <a-icon type="loading" v-show="inputDisabled" />
        <a-input
          ref="queryDataName"
          v-model="queryData.name"
          :disabled="inputDisabled"
          placeholder="请输入自定义页面名称"
          class="updateInput"
          allowClear
          @pressEnter="namePressEnter"
          @blur="namePressEnter"
          @change="changeQueryDataName"
        ></a-input>
      </div>
    </div>

script代码块

data() {
    return {
      //数据
   	  queryData:{
		name:'',
		id:''
	  },
	  //显示隐藏input
      isUpdateName: false,
      //禁用input
      inputDisabled: false,
      //解决点击input清空按钮blur比click事件优先的标识
      clickFlag: false,
    }
},
methods: {
    //判断是否清空数据
    changeQueryDataName(row) {
      if (row.type == 'click') {
        //触发清除
        this.clickFlag = true
      }
    },
    //修改名称
    namePressEnter() {
      setTimeout(() => {
        if (this.clickFlag) {
          this.clickFlag = false
          return
        }
        if (this.queryData.name === '' || this.queryData.name.length >= 50) {
          this.$message.warning('名称最大限制为50个字符且不允许为空!')
          this.$nextTick(() => {
            this.$refs.queryDataName.focus()
          })
          return
        }
        this.inputDisabled = true
        //setEditForm是我这边后端定义的接口
        setEditForm({ id: this.queryData.id, name: this.queryData.name })
          .then((res) => {
            this.inputDisabled = false
            this.$message.success('页面名称修改成功')
            this.isUpdateName = false
            this.$emit('updateName')
          })
          .catch((err) => {
            this.inputDisabled = false
            this.$message.error(err.message)
          })
      }, 200)
    },
    //重命名触发
    updateNmae() {
      this.isUpdateName = true
      this.$nextTick(() => {
        this.$refs.queryDataName.focus()
      })
    }
}

style代码块

  .queryDatatitle {
    cursor: pointer;
    color: var(--titleCustomColor);
    font-weight: bold;
    font-size: 17px;
    align-items: center;
    display: flex;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    .updateInput {
      width: 350px;
    }
  }

注意点:

1.失去焦点并鼠标点击外部 dom 元素一次触发事件@blur=“blur”

2.input 定义 ref 为 queryDataName,然后通过如下获取焦点,必须要加$nextTick,不然会报错获取不到dom元素

 this.$nextTick(() => {
          this.$refs.queryDataName.focus()
    })

3.点击input输入框的清空按钮会触发input的blur的事件
可以通过onChange事件触发的方法,根据type来判断出是输入还是点击清除

   changeQueryDataName(row) {
      if (row.type == 'click') {
        console.log('触发清除')
      }
    },

4.ant design的官网地址