首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >当使用Vue路由器单击嵌入在视图中的路由器链接时,路由器视图将不会更新

当使用Vue路由器单击嵌入在视图中的路由器链接时,路由器视图将不会更新
EN

Stack Overflow用户
提问于 2020-11-29 19:05:33
回答 2查看 621关注 0票数 2

我有一个相关的内容部分在我的贴子页底部,显示其他相关的帖子。

当点击相关内容时,我希望路由器能够更新页面。然而,这种情况并没有发生。url正在更改,但视图不更新。

组件

Post.Vue

代码语言:javascript
复制
<template>
  <div class="post-container" >
    <router-view name="PostContent">
      <h2>test</h2>
    </router-view>
    <div v-if="currentPost !== ''">
      <img :src="currentPost.jetpack_featured_media_url" />
      <!-- <h1 v-html="currentPost.title.rendered"></h1> -->
      <div
        v-html="currentPost.excerpt.rendered"
        class="post-excerpt-container"
      ></div>
      <div
        v-html="currentPost.content.rendered"
        class="post-content-container"
      ></div>
    </div>
    <section class="related-content">
       <h2>Related Content:</h2>
       <p v-if="currentPost.title !== undefined">If you enjoyed {{currentPost.title.rendered}}, we think you'll like:</p>
      <div class="related-content-container" v-for="relatedPost in relatedPosts" :key="relatedPost.id" :data-id="relatedPost.id">
          <router-link :to="{name:'Post',params:{id:relatedPost.id}}">
          <RelatedCard :post='relatedPost' />
          </router-link>
      </div>
    </section>
  </div>
</template>

<script>
import { mapState } from "vuex";
import RelatedCard from '@/components/RelatedCard.vue';
export default {
  name:"Post",
  components:{RelatedCard},
  data() {
    return {
      currentPost: "",
      id: this.$route.params.id,
      relatedPosts: []
    };
  },
  computed: {
    ...mapState({
      baseAPIURL: (state) => state.baseAPIURL,
      posts: (state) => state.posts,
    }),
  },
  created() {
    console.log('created')
    fetch(`${this.baseAPIURL}/posts/${this.id}?_embed`)
      .then((resp) => resp.json())
      .then((post) => {
        this.currentPost = post;
      });
  },
  methods: {
    pushToRelated() {      
      this.posts.forEach((post) => {
        post.relatedScore = 0;
        if (post.id !== this.currentPost.id) {
          post._embedded['wp:term'][0].forEach(el=>{
            for(let i  = 0;i < this.currentPost._embedded['wp:term'][0].length;i++){
              if (el.name === this.currentPost._embedded['wp:term'][0][i].name){
                post.relatedScore = post.relatedScore + 3
              }
            }
          })
          post._embedded['wp:term'][1].forEach(el=>{
            for(let i  = 0;i < this.currentPost._embedded['wp:term'][1].length;i++){
              if (el.name === this.currentPost._embedded['wp:term'][1][i].name){
                post.relatedScore = post.relatedScore + 1
              }
            }
          })
        }
      });
      this.relatedPosts = this.posts.sort((a,b)=>a.relatedScore - b.relatedScore).reverse().slice(0,5)
    }
  },
  watch: {
   currentPost: function () {
     if (this.posts.length > 0){
      this.pushToRelated();
     }
    },
  }
};
</script>

RelatedCard.vue

代码语言:javascript
复制
<template>
    <div class="related-card">
      <div>
        <img v-if="post._embedded['wp:featuredmedia'][0].media_details.sizes.medium_large !== undefined" :src="postImageML" alt="" />
        <img v-else :src="postImage" alt="">
      </div>
      <div>
        <h2 v-html="post.title.rendered"></h2>
        <p v-html="post.excerpt.rendered"></p>
      </div>
    </div>
</template>

<script>
export default {
  props: {
    post: Object,
  },
  computed:{
    postImageML(){
      return this.post._embedded['wp:featuredmedia'][0].media_details.sizes.medium_large.source_url
    },
    postImage(){
      return this.post._embedded['wp:featuredmedia'][0].media_details.sizes.full.source_url
    }
  },
};
</script>

我的路由器Config

代码语言:javascript
复制
const routes = [
  {
    path: "/",
    name: "Home",
    component: Home,
  },
  {
    path: "/list",
    name: "List",
    component: List,
  },
  { path: "/database", name: "Database", component: Database },
  {path:"/post/:id",name:"Post",component:Post}
];

const router = new VueRouter({
  routes,
});

export default router;

我尝试过的:

我尝试过使用$router.go()。这在更新页面时起了作用。然而,在改版后,我的观察人员没有正常工作。另外,我失去了用户返回到前一篇文章的能力。

我还尝试在包装器元素上使用组件键,但没有成功。

任何关于为什么会发生这种情况以及我能做些什么来解决它的建议都是很棒的。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-11-29 20:28:25

当您输入当前呈现其组件的路由时,默认情况下该组件将被重用,因此不调用created。你可以:

使用:key

使用键意味着如果密钥不匹配,组件就不会被重用。将路由器视图更改为:

代码语言:javascript
复制
<router-view :key="$route.fullPath" />

每个单独的param将改变路由器的完整路径,并给出一个唯一的密钥。

使用updated钩子

created不同,这是在param更改时调用的。但是在第一次加载时没有像created那样调用它,所以您需要使用这两个挂钩。

代码语言:javascript
复制
created() {
  // Do whatever when the component loads
},
updated() {
  // Do whatever when the component updates
}
票数 3
EN

Stack Overflow用户

发布于 2020-11-29 19:10:32

我还没有阅读您所有的代码,但是尝试将历史记录模式添加到路由器。

代码语言:javascript
复制
const router = new VueRouter({
  routes,
  mode: 'history', // Add this
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65064006

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档