vue elmentUI el-input自动聚焦

场景:双击标题可修改标题,失焦进行标题保存
实现:因为input页面初始化的时候是隐藏的,设置autofocus失效,最终利用自定义指令实现功能

<div class="head">
    <span v-show="!showEditName" @dblclick="tpEdit">{{name}}</span>
    <el-input
       v-show="showEditName"
       v-model="tpEditName"
       v-focus="showEditName"
       maxlength="30"
       clearable
       placeholder="请输入标题"
       @blur="sureEdit"
       style="width:260px">
   </el-input>
</div>
<script>
  name: 'home',
  data() {
       return {
            name: "标题",
            showEditName: false,
            tpEditName: ''
       }
  }
  methods: {
       tpEdit() {
             this.showEditName = true
             this.tpEditName = this.name
        },
        sureEdit() {
             const tpEditName = this.tpEditName.trim()
             const name = this.name.trim()
             if (tpEditName.length > 0 && tpEditName !== name) {
                    //  这里请求修改标题的接口
             } else if (tpEditName.length === 0) {
                    this.$message.error('标题不能为空')
                    this.showEditName = false
             } else {
                    this.showEditName = false
             }
        }
  },
 directives: {
    focus: {
        inserted(el, { value }) {
            if (value) {
                el.children[0].focus()
             }
         },
       // 更新判断
        update: function(el, { value }) {
            if (value) {
                el.children[0].focus()
             }
        },
        // 更新完成
        componentUpdated: function(el, { value }) {},
      }
    }
</script>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容