首页 > 解决方案 > 我如何让按钮隐藏未完成的任务

问题描述

这是 Jsfiddle:https ://jsfiddle.net/zxo35mts/1/

本质上,我试图让按钮在单击时隐藏所有未完成的任务,并在再次单击时再次显示它们,但我不知道该怎么做

<div id="root">

    <h1>
        All Tasks
    </h1>

    <ul>
        <li v-for="task in tasks" v-text="task.description"></li>
    </ul>
    <button @click="hideIncompleteTasks">show only completed</button>

</div>

<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>

<script>
    new Vue({

        el: "#root",

        data: {

            tasks: [

                { description: "go to the store", completed: true },
                { description: "finish screencast", completed: false },
                { description: "make donation", completed: false },
                { description: "clear inbox", completed: false },
                { description: "make dinner ", completed: false },
                { description: "clean room", completed: true },

            ]

        },
        methods: {

            hideIncompleteTasks() {
                if (!this.tasks.completed) {

                }
            }

        },

    })
</script>

标签: vue.jsvuejs2vue-componentv-for

解决方案


添加另一个showCompleted可以通过按钮单击事件更新的属性,然后添加另一个shownTasks基于第一个属性调用的计算属性:


    new Vue({

        el: "#root",

        data: {

            tasks: [

                { description: "go to the store", completed: true },
                { description: "finish screencast", completed: false },
                { description: "make donation", completed: false },
                { description: "clear inbox", completed: false },
                { description: "make dinner ", completed: false },
                { description: "clean room", completed: true },

            ],
          showCompleted:false

        },
        computed:{
          shownTasks(){ return this.showCompleted?this.tasks.filter(task=>task.completed):this.tasks;}
        },
        methods: {

            hideIncompleteTasks() {
               this.showCompleted=!this.showCompleted
            }

        },

    })

然后渲染shownTasks类似:


 <ul>
        <li v-for="task in shownTasks" v-text="task.description"></li>
    </ul>
    <button @click="hideIncompleteTasks">show only completed</button>


推荐阅读