【发布时间】:2021-05-30 01:21:46
【问题描述】:
我在 VUE 中创建了一个简单易用的应用。
为了删除一张卡片(每张卡片都是一个对象,其 id、title 和 description 位于 App.vue 组件的 state 中),我将 App 中的 id 作为道具传递给 TaskList 和按钮(删除)在任务组件中。然后为了触发 deleteTask 函数,我再次将 id 从 Task 发送到 TaskList 再发送到 App。
这种方法有效。但是,这种长链的排放是否被认为是好的做法?有没有更好的方法?
App.vue
<template>
<div>
<TaskList :tasks="tasks" @id="deleteTask"/>
<Form :length="tasks.length" @addTask="addNewTask" />
</div>
</template>
<script>
import TaskList from './components/TaskList';
import Form from './components/Form';
export default {
name: 'App',
components: { TaskList, Form },
data() {
return {
tasks: [
{
id: 1,
title: 'Hello World',
description: 'this is the world'
},
{
id: 2,
title: 'Hello Mars',
description: 'this is the mars'
},
{
id: 3,
title: 'Hello Jupiter',
description: 'this is the jupiter'
}
]
}
},
methods: {
addNewTask(taskObject) {
const listOfTasks = this.tasks.concat(taskObject);
this.tasks = listOfTasks;
},
deleteTask(id) {
const filteredList = this.tasks.filter(element => {
return element.id != id;
})
this.tasks = filteredList;
}
}
}
</script>
任务列表.vue
<template>
<div class="taskList" v-bind:key="task" v-for="task in tasks">
<Task :title="task.title" :description="task.description" :id="task.id" @id="sendId"/>
</div>
</template>
<script>
import Task from './Task';
export default {
props: ['tasks'],
components: { Task },
methods: {
sendId(id) {
this.$emit('id', id);
console.log(id)
}
}
}
</script>
Task.vue
<template>
<div class="task">
<h1>{{ title }}</h1>
<p>{{ description }}</p>
<button @click="passId">Delete</button>
</div>
</template>
<script>
export default {
props: ['title', 'description', 'id'],
methods: {
passId() {
this.$emit('id', this.id);
}
}
}
</script>
【问题讨论】:
-
Vuex 可以解决这个问题。它为您的应用创建了一个全球商店。
标签: javascript vue.js vuejs3