首页 > 解决方案 > 为什么 Vue 将我的 v-if 评估为假,尽管它是真的?

问题描述

当我运行它时,vue 返回第二个模板,即使是groups.length is equal1。为什么?它与安装发生的顺序和评估 v-if 的顺序有关吗?再次,我确定groups.length评估为 1。我尝试过使用beforeMount,而不是mounted,但这没有用。

<template v-if = "groups.length">
    <ul id = "groupList">
        <li v-for = "group in groups">
            <a>{{ group.name }}</a>
        </li>
        <div class = "addSidebar">
            <label class = "btn" for = "modal-1">+</label>
        </div>
    </ul>
</template>
<template v-else>
    <ul id = "groupList">
        <li>
            <a>You have not created/joined any groups.</a>
        </li>
        <div class = "addSidebar">
            <label class = "btn" for = "modal-1">+</label>
        </div>
    </ul>
</template>

<script>
export default {
    data() {
        return {
            groups: {}
        }
    },
    methods: {
        getGroups() {
            axios.get('groupList').then((response) => {
                this.groups = response.data
            }).catch((errors) => {
                console.log(errors)
            });
        },
        newModal() {
            $('#modal').modal('show');
        }
    },
    mounted() {
        this.getGroups()
    },
    name: "groupList"
}
</script>

标签: laravelvue.jsvue-component

解决方案


你需要使用javascript异步

https://www.w3schools.com/js/js_async.asp

<template >
    <div>
        <ul id="groupList" v-if="groups.length">
            <li v-for="group in groups" :key="group.id">
                <a>{{ group.name }}</a>
            </li>
            <div class="addSidebar">
                <label class="btn" for="modal-1">+</label>
            </div>
        </ul>

        <ul id="groupList" v-else>
            <li>
                <a>You have not created/joined any groups.</a>
            </li>
            <div class="addSidebar">
                <label class="btn" for="modal-1">+</label>
            </div>
        </ul>
    </div>
</template>
<script>
export default {
    data() {
        return {
            groups: {},
        };
    },
    methods: {
        async getGroups() {
            await axios
                .get("groupList")
                .then((response) => {
                    this.groups = response.data;
                })
                .catch((errors) => {
                    console.log(errors);
                });
        },
        newModal() {
            $("#modal").modal("show");
        },
    },
    async mounted() {
        await this.getGroups();
    },
    name: "groupList",
};
</script>

在您的代码中,您创建了 2<template >这不是有效的语法,并且 vue 应该有根元素

https://vuejs.org/v2/guide/components.html#A-Single-Root-Element


推荐阅读