laravel - 为什么 Vue 将我的 v-if 评估为假,尽管它是真的?
问题描述
当我运行它时,vue 返回第二个模板,即使是groups.length is equal
1。为什么?它与安装发生的顺序和评估 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>
解决方案
你需要使用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
推荐阅读
- jquery - 动态追加 Json 数据无法正常工作
- c# - 无法转换类型错误,但两种类型都一样?
- react-native - 如何在不使用本机反应创建文件的情况下从数组缓冲区播放音频
- mysql - 如何在不使用字段名称的情况下从 Groovy 中的 MySQL 表行中获取所有字段值?
- nuget - 无法解决安装 Nuget 包的依赖关系
- javascript - 索引页面不在页面顶部打开,它直接在页面表单上打开
- java - java代码风格:当通用合同不足时返回特定的Map实现
- php - Laravel Eloquent,使用 whereIn 获取 ids 数组中的所有数据?
- error-handling - 当我的键是骡子中的动态时,如何从属性文件中获取值?
- javascript - RazorPay,我怎样才能获得付款失败的价值?