【问题标题】:Why is a div v-for with a calculated property not render?为什么具有计算属性的 div v-for 不呈现?
【发布时间】:2020-06-26 05:13:21
【问题描述】:

为避免将v-ifv-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


【解决方案1】:

从数据对象中删除adminComment,只保留计算属性,注释初始应该是一个空数组:

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

【讨论】:

    猜你喜欢
    • 2017-04-16
    • 2017-11-23
    • 2018-07-29
    • 1970-01-01
    • 2018-03-02
    • 2021-09-02
    • 2021-06-18
    • 2016-09-17
    • 1970-01-01
    相关资源
    最近更新 更多