Javascript 为什么具有计算属性的div v-for不能渲染?
为避免使用Javascript 为什么具有计算属性的div v-for不能渲染?,javascript,vue.js,vuejs2,axios,vue-component,Javascript,Vue.js,Vuejs2,Axios,Vue Component,为避免使用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&
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>
但是如果我没有指定admincoment:[]
,那么我会在控制台中得到一个带有错误的无效页面:
Error in render: "TypeError: Cannot read property 'filter' of null"
及
帮我弄清楚。当然,更重要的不是纠正错误,而是显示div,从数据对象中删除
admincoment
,只保留computed属性的属性,并且comment最初应为空数组:
data(){
return {
comments: [],
feed_isVisible: false,
}
},
computed: {
adminComment: function () {
return this.comments.filter(function (comment) {
return (comment.user === 'admin')
})
}
},
axios响应应类似于:
axios.get('/api/comments')
.then(function(response) {
vm.comments = response.data
})
},
getComments
使用异步回调填充comments
数据,在填充comment
数据之前,将计算您的计算值。
data(){
return {
comments: [],
feed_isVisible: false,
}
},
computed: {
adminComment: function () {
return this.comments.filter(function (comment) {
return (comment.user === 'admin')
})
}
},
axios.get('/api/comments')
.then(function(response) {
vm.comments = response.data
})
},