【问题标题】:Vue component not re rendering on new $router.pushVue 组件不会在新的 $router.push 上重新渲染
【发布时间】:2018-04-19 21:22:27
【问题描述】:

所以我有这个 SearchResult 组件,当 vue-router 调用它时,它会从 YouTube API v3 获取一个对象,并将接收到的对象作为道具传递给几十个子组件。我有一个搜索栏,它使用$router.push(/search/ + this.query) 更改路线并显示此组件。

问题是它在第一次或当我使用来自其他路线的搜索时效果很好。但是,当我再次搜索时,组件 不会 重新呈现来自 API 的新结果。即使我为this.$route.params.query 添加了一个观察者。这是 SearchResult.vue 组件。

<template>
<div>
  <app-banner></app-banner>
  <div v-if="resultIds">
    <div v-for="resId in resultIds.items">
      <vid-preview :vidId="resId.id.videoId"></vid-preview>
    </div>
  </div>
</div>
</template>

<script>
import axios from 'axios'

export default {
  data() {
    return {
      resultIds: null,
      errors: []
    }
  },
  watch: {
    '$route.params.query' (newQuery, oldQuery) {
      this.$router.push('/search/' + newQuery) //This code executes but no change visible on screen.
    }
  },
  created() {
    axios.get(`https://www.googleapis.com/youtube/v3/search/`, {
      params: {
        part: 'id',
        q: this.$route.params.query,
        order: 'relevance',
        maxResults: '50',
        key: '{API KEY}'
      }
    }).then(res => {
      this.resultIds = res.data;
    }).catch(e => {
      this.errors.push(e);
    })
  }
}
</script>

【问题讨论】:

    标签: javascript web vue.js vuejs2 vue-component


    【解决方案1】:

    应该是这样的:

    '$route.params.query' (newQuery, oldQuery) {
      this.$router.push({
        path: '/search/' + newQuery
      })
    }
    

    目前:

    '$route.params.query' (newQuery, oldQuery) {
      this.$router.push('/search/' + newQuery) //This code executes but no change visible on screen.
    }
    

    【讨论】:

    • @samayo 感谢您的编辑,我试图让它像代码一样 :)
    • 没问题。下次突出显示您的代码块并从编辑器工具中单击{}
    • 不应该把 $route.params.query 用单引号括起来吗??
    • 不幸的是,它似乎仍然不适合我。该组件仍未重新渲染。
    • 问题可能this.$router不工作,试试console.log(this)看看是否返回vue实例
    猜你喜欢
    • 1970-01-01
    • 2017-11-09
    • 2020-02-13
    • 2020-06-18
    • 2020-08-08
    • 2018-10-14
    • 2020-07-19
    • 2017-05-08
    • 2020-07-09
    相关资源
    最近更新 更多