Vue Router is not updating the router view when the router link clicked is embedded within the view

I have a section called Related Content located at the bottom of my posts page, which displays other related posts.

When I click on the Related Content, I expect the router to update the page. However, it seems that although the URL changes, the view does not update accordingly.

Key Elements

Post.Vue

<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

<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>

My Router Configuration

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;

What I Have Tried:

I attempted to use $router.go(), which did update the page but caused issues with my watchers and prevented users from returning to the previous post. Additionally, I experimented with component keys on the wrapper element without success.

If you have any insights into why this issue is occurring or suggestions for a solution, please feel free to share them.

Answer №1

Upon entering a route with a currently rendered component, the default behavior is to reuse the component, resulting in the created method not being called. To work around this, you have a couple of options:

Option 1: Utilize a :key

By using a key, the component will not be reused unless the key matches. Update your router-view like so:

<router-view :key="$route.fullPath" />

Each parameter change will alter the full path of the router and generate a unique key.

-OR-

Option 2: Employ the updated hook

The updated hook gets triggered whenever a parameter changes. Unlike created, it does not get called on the initial load, so you may need to utilize both hooks for desired functionality. Keep in mind that factors other than parameter changes can also activate the updated hook, so refrain from performing resource-intensive tasks within it.

created() {
  // Implement actions upon component initialization
},
updated() {
  // Implement actions upon component updates
}

Answer №2

I haven't gone through your entire code, but I suggest implementing the history mode in the router.

const router = new VueRouter({
  routes,
  mode: 'history', // Make sure to add this line
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

You are trying to reference the property or method "subscribed" during the render process in Vue.js, but it is not defined on

Within my Vue subscribe-button component, I have included all the necessary parts: props, computed properties, and methods. In the computed section, I have defined the subscribed property. However, I am encountering an error: " [Vue warn]: Property o ...

Learn the process of transferring information from a dynamically generated table to a database using PHP

After creating a table using PHP dynamically, I am facing an issue with updating some cell values based on user input. I have provided my code below. I tried using [] in the names attribute to make names an array as suggested on Stack Overflow, but it didn ...

Iteratively sift through data for boolean value

My navigation dynamically retrieves routes from the vue-router, eliminating the need for manual addition. Within these routes, there is a boolean key named "inMenu" in both parent and child routes. I have successfully filtered out the parent routes based ...

Issues arise when attempting to delete messages that have already been retrieved

Having trouble removing messages from a specific user without any success: bot.js client.on("message", (message) => { if (message.content === '$deleteuser') { message.channel.fetchMessages({limit: 10}).then(collec ...

Employing a pair of interdependent v-select components to prevent any duplicate entries

I am currently working with two v-select boxes that share similar data. In my scenario, I extract attachments from an email and load them into an array. The issue I encountered is that the first select box should only allow the selection of one document, w ...

What scenarios call for the utilization of setScriptTimeout?

When using Selenium WebDriver, there is a method called setScriptTimeout(time, unit). The description of this method states that it Specifies the time allowed for an asynchronous script to finish executing before an error is thrown. If the timeout is set ...

ng-class not functioning properly when invoked

In my controller, I have the following function: $scope.menus = {}; $http.get('web/core/components/home/nav.json').success(function (data) { $scope.menus = data; $scope.validaMenu(); }).error(function () { console.log('ERRO') }); ...

Matching request parameters with a JSON object using node.js and express framework

After uncommenting the lines, the code runs smoothly. However, whenever I enable the 'else' statement, I consistently receive a 'not found' message even when there is a match between req.params.code and data.airports[i].code. var exp ...

Difficulties encountered when adjusting the size or reducing the images in a Cycle2 slideshow

Greetings to all fellow coders! Thank you for taking the time to read this post. I am currently facing a challenge in my web development project where I am trying to make my Cycle 2 slideshow images resize and reposition alongside other divs when the wind ...

Problem with roles assigned through reactions on Discord

I've been working on a discord bot reaction roles command and everything seems to be going smoothly, except for one issue that I'm facing. After booting up the bot and running the command to create the embed, everything works fine. However, when ...

Tips for creating text that adjusts to the size of a div element

I'm currently working on developing my e-commerce website. Each product is showcased in its own separate div, but I've encountered a challenge. The issue arises when the product description exceeds the limits of the div, causing it to overflow ou ...

How about this: "Unveil the beauty of dynamically loaded

var request = new Request({ method: 'get', url: 'onlinestatusoutput.html.php', onComplete:function(response) { $('ajax-content').get('tween', {property: 'opacity', duration: 'long&apos ...

Error Encountered when Using JQuery AJAX: Unexpected Identifier Syntax Issue

I've been struggling with a strange error for quite some time now. I want to believe that this is one of those errors where the solution will magically appear, but only time will tell. Here's the piece of code causing the issue: var images = ...

creating dynamic column headers with JavaScript

I am looking for a way to make the column names dynamic so that I don't have to manually update them every time. Here is my code snippet: jqGrid11.prototype = { display : function() { $('body').append(this.html.join("")); $("#jqGrid").j ...

Optimal techniques for leveraging CSS within Mui and Reactjs

Just starting out with mui, I'm currently working on styling CSS for mui components like so <Typography variant="h5" sx={{ fontWeight: "bold", color: "#1a759f", display: "flex", ...

Is there a way to showcase the uploaded file contents on the current page without the need to refresh?

Is there a way to display the contents of an uploaded file on the same HTML page without opening a new tab or refreshing it? I have the following HTML and PHP codes for reading an uploaded file in a separate page, but I want to integrate it into the same H ...

The useEffect hook is executed only once and will not fetch data again upon refreshing the page

There's this component in my project that fetches data from a website and attempts to extract its keys. The issue I'm facing is that it functions correctly the first time, but upon refreshing the page or saving the project in VSCode (which trig ...

What is the process of retrieving an image file in a Java post API when it is being transmitted as form data through Jquery?

I have encountered an issue with fetching file data in my POST API when utilizing three input file fields in JavaScript. The values are being sent using formdata in jQuery upon clicking the submit button, but I am experiencing difficulties in retrieving th ...

Exploring the power of Vuex getters with customized arguments

I built a simple Vue and Vuex based app that displays a table with items like this: <div class='items'> <div v-for='item in items'> <span> {{ item.name }} </span> <router-link :to='"update/" + ...

I came across a forum where someone mentioned encountering a similar issue but unfortunately, no solution was provided. Currently, I am working on setting up a reaction roles system but despite embedding the message, the role is not being

I am currently working on setting up a reaction roles system for my Discord server, but I have encountered a significant issue that may seem minor to most. The problem is that although my bot successfully sends embeds with corresponding emojis for the ro ...