Vue:如何通过按钮点击动态切换任务列表显示状态?
Solution for Toggling Task List View
Got it, let's fix this up with minimal changes! Here's how you can toggle between showing incomplete and completed tasks while updating the heading:
Updated HTML
<div id="computedList"> <h2>All Tasks</h2> <ul> <li v-for="task in tasks" v-text="task.description"></li> </ul> <h2>{{ message }}</h2> <ul> <li v-for="task in filteredTasks" v-text="task.description"></li> </ul> <button @click="toggleClass">Toggle Completed/Incomplete</button> <br> </div>
Updated JavaScript
var appb = new Vue({ el: '#computedList', data: { message: 'Incomplete tasks', tasks: [ {description: 'Begin to study Vue', completed: true}, {description: 'Begin with the testapp', completed: true}, {description: 'Begin to study the ABB webbapp', completed: false}, {description: 'Begin to study Angular2', completed: false}, ], showCompleted: false // New flag to track view state }, computed: { filteredTasks() { // Filter based on the showCompleted flag return this.tasks.filter(task => this.showCompleted ? task.completed : !task.completed); } }, methods: { toggleClass() { this.showCompleted = !this.showCompleted; // Update heading text based on the new state this.message = this.showCompleted ? 'Completed tasks' : 'Incomplete tasks'; } }, });
Key Changes Explained:
- Added a
showCompletedboolean indatato track which set of tasks we're displaying - Renamed the computed property to
filteredTasks(more descriptive) and adjusted the filter logic to use theshowCompletedflag - Rewrote the
toggleClassmethod to flip theshowCompletedflag and update themessageheading text in one go - Updated the template to use
filteredTasksinstead ofincompleteTasks
This keeps the code concise and achieves exactly what you need—clicking the button switches the list between incomplete and completed tasks, with the heading updating automatically.
内容的提问来源于stack exchange,提问作者josefdev
相关产品推荐
相关产品推荐

