如何在Vue.js中正确设置v-if的值

时间:2018-01-13 12:30:48

标签: javascript vue.js

我试图通过制作这个任务应用来熟悉Vue.js。当我尝试更新v-if="!task.deleted"值以显示删除时的某些转换时,虽然该任务已成功从数据库中删除,但它不会从页面中删除。

我尝试删除任务后再次检索任务,但我不认为这是更新列表的正确方法(也许我错了)。我也无法使用此方法获得过渡效果。

以下是我的单个文件组件Tasks.vue中的代码:

<template>
...
<table class="table">
    <tbody>
        <tr :tasks="tasks" v-for="task in tasks" :key="task.id">
            <transition name="fade">
                <task-item v-if="!task.deleted" v-on:singleTaskDeleted="taskDeleted(task)" :task="task"></task-item>
            </transition>
        </tr>
    </tbody>
</table>
...
</template>

<script>

import TaskInput from './TaskInput.vue';
import TaskItem from './TaskItem.vue';

export default {
    data : function (){
        return {
            dbTasks : {}
        }
    },
    computed : {
        tasks : function (){
            return this.dbTasks;
        }
    }, 
    components: {
        TaskItem, TaskInput
        },
    methods: {
        getTasks(){
            axios.get('tasks')
            .then( response => {
                this.dbTasks = response.data;
            })
            .catch(function (error) {
                console.log(error);
            });
        },

        /* Is this the right way to set `deleted`?? */

        taskDeleted(task){
            task.deleted = 1;
        }
    },
    created() {
            this.getTasks();
        },
    mounted() {
        console.log('Component mounted.')
    }
}
</script>

TaskItem.vue组件设置如下:

<template>
    <td class="task-item" v-if="!task.deleted"
                        v-on:task-deleted="taskDeleted(task)" >
        {{singleTask.id}} - {{singleTask.text}} 
        <button type="button" class="close" aria-label="Close"
            v-on:click="deleteTaskItem(singleTask.id)">
        <span aria-hidden="true">&times;</span>
    </button>
    </td>
</template>

<script>
    export default {
        props: ['task'],
        data : function () {
            return {
                singleTask : this.task,
                deleted : false,
            };
        },
        mounted() {
            console.log('Component TaskItem mounted.')
        },
        methods: {
            deleteTaskItem : function (tid) {
                axios.delete('tasks/'+tid, {
                    csrf : this.csrf,
                    id : this.singleTask.id
                })
                .then( response => {
                    this.$emit('singleTaskDeleted');
                    console.log('Delete event emitted');
                    console.log(response);
                })
                .catch(function (error) {
                    console.log(error);
                });
            }
        }
    }
</script>

0 个答案:

没有答案