【发布时间】:2020-06-26 05:13:21
【问题描述】:
为避免将v-if 与v-for 一起使用,如手册建议的那样,我使用以下结构:
<template>
<div id="fastopinion">
<div v-for="comment in adminComment"
:key="comment.id"
v-show="feed_isVisible">
<div id="user">{{ comment.user }}</div>
</div>
</div>
</template>
<script>
import axios from 'axios'
export default {
data() {
return {
comments: null,
feed_isVisible: false,
adminComment: [],
}
},
computed: {
adminComment: function () {
return this.comments.filter(function (comment) {
return (comment.user === 'admin')
})
}
},
mounted()
{
let vm = this;
vm.getComments();
},
methods: {
getComments() {
let vm = this
axios.get('/api/comments')
.then(function(response) {
vm.comments = response.data.data
})
},
},
}
</script>
但由于某种原因,这个 div 没有显示出来。在控制台中我得到一个错误:
The computed property "adminComment" is already defined in data.
但是如果我不指定adminComment: [],那么我会在控制台中得到一个无效页面并出现错误:
Error in render: "TypeError: Cannot read property 'filter' of null"
和
Cannot read property 'filter' of null
at VueComponent.adminComment
帮我解决这个问题。更重要的当然不是更正错误,而是显示div
【问题讨论】:
-
getComments使用异步回调填充comments数据,并且您的计算值将在填充comment数据之前计算。
标签: javascript vue.js vuejs2 axios vue-component