HTML

<span :style="{ display : displayTitle }" @dblclick="showInput()">
  {{ node.title }}
</span>
<input :style="{ display : displayTitleInput }" type="text" 
       @blur="hideInput1" @keydown="hideInput2" 
       @input="changeTitle(node.id , $event.target.value)" 
       :value="node.title">

JS

data() {
  return {
      displayTitle: "inline-block",
      displayTitleInput: "none"
    };
},
showInput() {
    this.displayTitle = "none"
    this.displayTitleInput = "inline-block"
},
hideInput1() {
   this.displayTitle = "inline-block"
   this.displayTitleInput = "none"
},
hideInput2(event) {
    if (event.keyCode === 13) {
        this.hideInput1()
    }
},

我是一名日本网络开发新手.对不起,我英语不好.

HTML在"v-for"(v-for="node in list")中.

双击文本时,文本变为<input>.

我想让它在出现的时候能够专注于输入.

我试过了,但没用.

HTML

<span :style="{ display : displayTitle }" @dblclick="showInput(node.id)">
  {{ node.title }}
</span>
<input :ref='"input_" + node.id' :style="{display:displayTitleInput}" type="text" 
       @blur="hideInput1" @keydown="hideInput2" 
       @input="changeTitle(node.id , $event.target.value)" 
       :value="node.title">

JS

showInput(id) {
    this.displayTitle = "none"
    this.displayTitleInput = "inline-block"

    this.$nextTick(this.$refs["input_" + id][0].focus())
},

控制台上没有错误,但不起作用.

推荐答案

您的主要问题是$nextTick接受回调函数,但您正在执行

this.$refs["input_" + id][0].focus()

立即你可以让你的代码正常工作

this.$nextTick(() => {
  this.$refs["input_" + id][0].focus()
})

然而,我认为你会遇到更多的问题,你的代码会变得更简单.

你会发现一个问题是,由于你的风格规则,当双击任何一个 node 输入时,你的所有 node 输入都会变得可见.

您可以将"editing"标志存储在node或单独的对象中的某个位置.

下面是一个通过以下方式简化代码的示例...

  1. 当在v-for循环中使用时,使用ref的数组性质,以及
  2. @keydown事件绑定上使用enter修饰符

new Vue({
  el: '#app',
  data: {
    list: [
      {id: 1, title: 'Node #1'},
      {id: 2, title: 'Node #2'}
    ],
    editing: {}
  },
  methods: {
    showInput(id, index) {
      this.$set(this.editing, id, true)
      
      this.$nextTick(() => {
        this.$refs.input[index].focus()
      })
    },
    hideInput(id) {
      this.editing[id] = false
    }
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue"></script>
<ul id="app">
  <li v-for="(node, index) in list">
    <span v-show="!editing[node.id]" @dblclick="showInput(node.id, index)">
      {{ node.title }}
    </span>
    <input v-show="editing[node.id]" type="text"
           ref="input" :value="node.title"
           @blur="hideInput(node.id)" @keydown.enter="hideInput(node.id)">
  </li>
</ul>

Vue.js相关问答推荐

如何将计算(computed)属性动态添加到Vue组件中?

VITE:无法为VUE单文件组件加载URL

Select 项目后,Vuetify v-select在select后面显示数字1

Vue 3:插槽属性 - 可以通过 props 传递数据吗?

在 v-for 中定义变量有什么问题吗?

如何在 Nuxt3 中使用 nuxtjs/auth-next 模块?

如何在 VUE.js 中重新刷新时保持多层 b-collapse 菜单打开?

在 Vuex 的状态下动态创建一个响应式数组

如何在 vue.js 构建中重命名 index.html?

事件 click点击的无效处理程序:未定义

vue js 中的 process.env.BASE_URL 是什么?

Vuejs 3 从子组件向父组件发出事件

交换数组项

如何确定 Vue 何时完成更新 DOM?

$set 不是函数

是否有 v-cloak 逆?

Vuejs 组件等待 facebook sdk 加载

vue-router 如何使用 hash 推送({name:"question"})?

如何在 vue3 中的setup方法中发出事件?

如何订阅store 模块