我可以使用哪种方法,每当组件上的支柱发生变化时,都会调用该方法

时间:2018-02-12 17:42:19

标签: vue.js vuejs2 render vue-component

我是Vue的新手。我将道具传递给子组件,当道具更改时,我使用watch来捕获更改并将它们分配给this.query。我可以在手表中记录这个变化,它正在工作。 prop值在页面上发生变化,但是mount不再被调用,只在第一次呈现组件时才调用它。我希望每次这些道具改变时都可以进行抓取。

我尝试使用updatedbeforeUpdate,但我无法在那里记录道具,所以不知道每次更改时我都可以获取数据。

<template>
  <div class="movie-list">
    <h1>{{ query }}</h1> 
    //At the moment I am just rendering the query which is changing as the prop changes but I want to be able to render movies incrementally from a fetch in mounted() as this.query changes
  </div>
</template>

<script>

export default {
  props: ['query'],
  name: 'SearchedMovies',
  data: function () {
    return {
      movies: []
    }
  },
  watch: {
    query: function(newVal){
      this.query = newVal
      console.log('query in watch', this.query); 
      //this is logging each time it changes
    }
  },
  updated () {
    console.log('query in updated', this.query);
    //this is not logging
  },
  beforeUpdate () {
    console.log('query in beforeUpdate', this.query);
    //this is not logging
  },
  mounted () {
    console.log('this is the query in SearchedMovies', this.query);
    //this is logging once when the component first renders
    //I want to be able to do a fetch here each time this.query changes and save the results to this.movies.
  }
}
</script>

1 个答案:

答案 0 :(得分:1)

watch道具更改后,query会被调用。您将新值 - 已经在query道具中 - 分配回query道具,这是一个坏主意,因为您不应修改道具。

只需将fetch放入watch回调中。