Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/447.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么具有计算属性的div v-for不能渲染?_Javascript_Vue.js_Vuejs2_Axios_Vue Component - Fatal编程技术网

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
               })
           },