【发布时间】:2020-01-20 13:46:09
【问题描述】:
我正在开发一个书籍跟踪器应用程序,它可以跟踪您已阅读或将要阅读的书籍。我在服务器端使用 Vue.js 和 Express.js。共有三个列表(类别)。我正在尝试应用按钮更改书籍类别的功能(即从“当前阅读”到“已完成”)。有用。但我必须重新加载整个页面才能看到结果。 所以我有一个组件“我的书”,其中包括组件“书单”,我将“listType”作为道具传递并呈现所有三个列表。在“书单”组件中,我有 v-for 渲染所有书籍并使用“书”组件和书对象作为道具。 'book' 组件有用于更改类别的按钮。因此,当我按下其中一个按钮时,我可以在服务器端更改 listType 并更新数据库条目,甚至重新渲染“书”组件,但是如果不刷新整个列表,我就无法达到我的书从一个列表移动到另一个列表的地步页。
//mybooks 组件
<template>
<BookList listType="current" />
<BookList listType="wantToRead" />
<BookList listType="finished" />
</template>
//书单组件
<template>
<div v-for="bookElement in bookList" :key="bookElement.id">
<Book :book="bookElement" />
</div>
</template>
<script>
export default {
data() {
return {
bookList: []
};
},
components: {
Book
},
props: ["listType"],
watch: {
"$route.query.searchDB": {
//once a query string search value changes, get list of books from server
immediate: true,
async handler(value) {
const list = (await BooksService.index(value)).data;
//filter books by categories
this.bookList = list.filter(element => {
return element.listType === this.listType;
});
}
}
}
</script>
// 图书组件
//template to render author, title etc
//and button for example
<button @click="changeTo('current', book.id)">Change to current</button>
<script>
import BooksService from "@/services/BooksService";
export default {
data() {
return {
isCurrent: false,
isLater: false,
isFinished: false
};
},
props: ["book"],
mounted() {
if (this.book.listType === "current") {
this.isCurrent = true;
} else if (this.book.listType === "finished") {
this.isFinished = true;
} else this.isLater = true;
},
methods: {
async changeTo(list) {
this.book.listType = list;
try {
await BooksService.put(this.book);
} catch (err) {
this.error = err;
}
}
}
};
</script>
【问题讨论】:
-
通常,如果您希望子组件的逻辑影响父组件,那么您需要将该逻辑上移到父组件。然后,您可以作为道具或
emit传递对它的引用。否则,即使孩子的状态发生变化,您的父组件也不会受到其孩子正在做什么的影响。
标签: javascript vue.js