You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 showCompleted boolean in data to track which set of tasks we're displaying
  • Renamed the computed property to filteredTasks (more descriptive) and adjusted the filter logic to use the showCompleted flag
  • Rewrote the toggleClass method to flip the showCompleted flag and update the message heading text in one go
  • Updated the template to use filteredTasks instead of incompleteTasks

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 03:28:26