要删除待办事项的项目,将$ emit升至2或1升?

问题描述 投票:0回答:1

我在这里有3个.vue:App.vue(默认),Todos.vue和Todoitem.vue。我正在关注https://www.youtube.com/watch?v=Wy9q22isx3U&t=2458中的教程。我可以知道为什么TodoItem.vue中的作者向App.vue发出两个级别的ID来执行删除方法吗?是最佳实践还是更好的编码风格?为Todos.vue做一个相同的工作就容易了吗?下面是我的任何评论的升级方法。

下面是我的TodoItem.vue代码

<template>
  <div class="todo-item" v-bind:class="{'is-complete':todoObj.completed}">
    <p>
      <input type="checkbox" v-on:change="markComplete" />
      {{todoObj.title}}
      <button @click="$emit('del-todo',todoObj.id)" class="del">x</button>
    </p>
  </div>
</template>

<script>
export default {
  name: "TodoItem",
  props: ["todoObj"], // todoObj is defined in the parent.
  methods: {
    markComplete() {
      this.todoObj.completed = !this.todoObj.completed;
    }
  }
};
</script>

<style scoped>
.todo-item {
  background: #f4f4f4;
  padding: 10px;
  border-bottom: 1px #ccc dotted;
}

.is-complete {
  text-decoration: line-through;
}

.del {
  background: #ff0000;
  color: #fff;
  border: none;
  padding: 5px 9px;
  border-radius: 50%;
  cursor: pointer;
  float: right;
}
</style>

下面是我的Todo.vue代码

<template>
  <div>
    <h1>Todo List2</h1>
    <!-- :key= and v-bind:key= are exactly the same. -->
    <!-- v-bind. Shorthand: : -->
    <div v-for="todo in ptodos" :key="todo.id">
      <!-- Define todoObj here which to be used in the child component, TodoItem -->
      <MyTodoItem v-bind:todoObj="todo" v-on:del-todo="deleteTodo" />
      <!-- del-todo is from the child. child goes up to parent and then to grandparent (App.vue) -->
    </div>
  </div>
</template>

<script>
import MyTodoItem from "./TodoItem.vue";

export default {
  name: "Todos",
  components: {
    MyTodoItem
  },
  props: ["ptodos"],

  methods: {
    deleteTodo(id) {
      this.ptodos = this.ptodos.filter(todo => todo.id !== id);
    }
  }
};
</script>

<style scoped>
</style>

下面是我的App.vue代码

<template>
  <MyToDos v-bind:ptodos="todos" />
</template>

<script>
import MyToDos from "./components/Todos";

export default {
  name: "App",
  components: { MyToDos },
  data() {
    return {
      todos: [
        {
          id: 1,
          title: "Todo One",
          completed: false
        },
        {
          id: 2,
          title: "Todo Two",
          completed: true
        },
        {
          id: 3,
          title: "Todo Three",
          completed: false
        }
      ]
    };
  }
};
</script>

<style>
* {
  box-sizing: border-box;
  margin: 0;
  padding: 0;
}

body {
  font-family: Arial, Helvetica, sans-serif;
  line-height: 1.4;
}
</style>
vue.js
1个回答
0
投票

如果您可以将其升级一个级别,那就更好了。在每个孩子上拥有多个道具可能是一种不受欢迎的做法,称为prop drilling

Vuex是避免嵌套道具的好选择。

热门问题
推荐问题
最新问题