我对vue中的计算属性非常困惑,因为它将数据应用于计算属性但不渲染?

时间:2017-11-04 13:49:14

标签: javascript laravel-5 vuejs2 vue-component

        computed: {
        filteredQuestions: function () {
            return this.allquestions.filter((question) => {
                return question.question.match(this.search)
            })
        }
    },

我有上面的计算属性,我在以下方式获取创建方法中的数据:

        created() {
        axios.get('/teacher/quiz/questions')
            .then((response) => {
                console.log(response.data);
                this.allquestions = response.data;

            })
            .catch(function (error) {
                console.log(error);
            });
    },

我已声明所有问题并在我的数据方法中搜索。 在实例化之后,数据不显示。 enter image description here

但同时它在vue检查工具中显示。 因此我对此感到困惑。幕后真的发生了什么? enter image description here

1 个答案:

答案 0 :(得分:1)

axios.get是异步操作。 所以,当程序第一次运行时,this.allquestions实际上仍然是undefined,并且您的计算方法失败。

我会在allquestions属性上将前端data声明为空数组。

参见代码:

<script>
export default {
  data() {
    return {
      allquestions: []
    }
  },
  computed: {
    filteredQuestions: function() {
      return this.allquestions.filter(question => {
        return question.question.match(this.search)
      })
    }
  },
  created() {
    axios
      .get('/teacher/quiz/questions')
      .then(response => {
        console.log(response.data)
        this.allquestions = response.data
      })
      .catch(function(error) {
        console.log(error)
      })
  }
}
</script>