0
点赞
收藏
分享

微信扫一扫

【vue】一个小bug和key的引入

Mezereon 04-03 06:00 阅读 1

在这里插入图片描述
点击master Vue!删除后该list后输入框中的Jerry消失了
在这里插入图片描述
原因:vue当你更改元素时会在真实的dom中渲染并更新list。这两个goal是两个dom元素,触发点击事件后,vue并不会删除第一个dom元素,而是把第二个dom元素的动态内容({{ goal }} - {{ index }})复制到第一个dom元素中,input元素仍然是老元素。

  <body>
    <header>
      <h1>Vue Course Goals</h1>
    </header>
    <section id="user-goals">
      <h2>My course goals</h2>
      <input type="text" v-model="enteredGoalValue" />
      <button @click="addGoal">Add Goal</button>
      <p v-if="goals.length === 0">
        No goals have been added yet - please start adding some!
      </p>
      <ul v-else>
        <li
          v-for="(goal, index) in goals"
          @click="removeGoal(index)"
        >
          {{ goal }} - {{ index }}<input type="text" @click.stop />
        </li>
      </ul>
    </section>
  </body>
</html>
const app = Vue.createApp({
	data() {
		return {
			enteredGoalValue: '',
			goals: [],
		};
	},
	methods: {
		addGoal() {
			this.goals.push(this.enteredGoalValue);
		},
		removeGoal(idx) {
			this.goals.splice(idx, 1);
		},
	},
});

app.mount('#user-goals');

为此引入key属性,可以在所有带有v-for的html标签使用,就像是id,给每个<li>添加不同的key属性,用来告知vue区分不同的<li>,这样做可以保证input中的内容不会丢失。

<li
          v-for="(goal, index) in goals"
          :key="goal"
          @click="removeGoal(index)"
        >
        ```
举报

相关推荐

0 条评论