Preserve Vue route parameters when the page is refreshed

I am looking for a way to pass a list of meta/props to multiple components based on the route. Currently, I have hardcoded the todo list, and it is not dynamically loaded. My current solution only works when I click from the list to go to an item. However, if I try to navigate directly or refresh the page, I lose the meta param.

My question is, how can I maintain this on page refresh? Is there a better approach to managing this?

You can check out the codesandbox example here.

// todo.vue
<template>
  <div class="todos">
    <h1>Todos</h1>
    <stats :value="total" label="Total"></stats>
    <stats :value="completed" label="Completed"></stats>
    <stats :value="pending" label="Pending"></stats>
    <todo-list :todos="todos"></todo-list>
  </div>
</template>

<script>
import Stats from "../components/Stats";
import TodoList from "../components/TodoList";

export default {
  name: "Home",
  components: {
    "todo-list": TodoList,
    stats: Stats
  },
  data() {
    return {
      limit: 20,
      todos: [
        {
          userId: 1,
          id: 1,
          title: "delectus aut autem",
          completed: false
        },
        {
          userId: 1,
          id: 2,
          title: "quis ut nam facilis et officia qui",
          completed: false
        }
      ]
    };
  },
  computed: {
    total: function() {
      return this.todos.length;
    },
    completed: function() {
      return this.todos.filter(function(todo) {
        return todo.completed === true;
      }).length;
    },
    pending: function() {
      return this.todos.filter(function(todo) {
        return todo.completed === false;
      }).length;
    }
  }
};
</script>
// todo list
<template>
  <ul v-if="todos.length > 0">
    <li v-for="todo in todos" :key="todo.id">
      <router-link :to="{name: 'singletodo', params: {id: todo.id, meta: todo}}">
        <span :class="todo.completed ? 'completed' : ''">{{ todo.title }}</span>
      </router-link>
    </li>
  </ul>
</template>

<script>
export default {
  name: "TodoList",
  props: ["todos"]
};
</script>

<style scoped>
.completed {
  color: gray;
  text-decoration: line-through;
}

ul {
  margin-top: 2em;
  margin-left: 1em;
}

li {
  list-style: square;
}
</style>
// Router config
const routes = [
  { path: "/", name: "home", component: Home },
  { path: "/about", name: "about", component: About },
  { path: "/todos", name: "todo", component: Todos },
  { path: "/todos/:id", name: "singletodo", component: TodoSingle }
];

const router = new Router({
  routes
});

Answer №1

Revamp your route structure with the following changes

// Router setup
const routes = [
  { path: "/", name: "home", component: Home },
  { path: "/about", name: "about", component: About },
  { path: "/todos", name: "todo", component: Todos },
  { path: "/todos/:id/:meta?", name: "singletodo", component: TodoSingle }
];

By including the meta parameter in the URL, you have the option to make it required by removing the question mark (?). This adjustment is necessary for seamless page refreshes.

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

The map's content shifts with every scroll of the mouse, rather than being controlled by the

After creating a custom control in leaflet, I noticed that when interacting with it using scroll or click, the underlying map is affected instead of the control itself. <CustomMapControl> <div className="custom-c ...

Clicking on the button in Angular 2+ component 1 will open and display component 2

I've been developing a Angular 4 application with a unique layout consisting of a left panel and a right panel. In addition to these panels, there are 2 other components within the application. The left panel component is equipped with buttons while ...

Applying VueJS filters to refine object values

Is there a way to verify if the value of "startAt" is present in an object and return its corresponding ID? Here is the object in question: [{ "id": "1234567", "createTimestamp": "2020", "name": { "action": "", "allDay": false, "categor ...

Ensure the backslashes are removed from the AWS Lambda string API response

I have an AWS Lambda function where I am sending a string as my final response let abc= `"phone_exist":"0","calls":"0","lastaction":"0"` callback(null,abc); Output: "\"phone_exist\":\"0\",\"calls\":\"0\",\"l ...

What is the process for including a new item in the p-breadcrumb list?

Having trouble getting my code to add a new item to the p-breadcrumb list on click. Any assistance would be greatly appreciated. Thank you in advance! Check out the live demo here ngOnInit() { this.items = [ {label: 'Computer'}, ...

Hover and Click Card Turning

My card can both hover and click, but there seems to be a small glitch. After clicking on the card and then moving the cursor away from the front, the hover effect doesn't work correctly. It immediately flips back to the front side. The hover effect ...

What is the best method for importing and utilizing child components exclusively?

Consider the following example with different components: first.js <div> <Route path='/' /> <Route path='/first' /> </div> second.js <div> <Route path='/second' /> <Redi ...

Trouble accessing the Google Hangout chat box through document.getElementById("id") method

Today I decided to investigate the design of the Google Hangout chatbox by using the Google Chrome inspector tool. After right-clicking on the chatbox text input element and inspecting it, here is what I discovered: <div id=":cb.f" class="vE dQ editabl ...

Internet database inventory

Looking for assistance in creating a list. <div id="ul"> <li></li> </div> ...

"Can you tell me more about the purpose of $cacheFactory

I am struggling to find information on the purpose and functionality of $cacheFactory in application development. According to the Angular Documentation, "Factory that constructs cache objects and gives access to them." -- $cacheFactory However, this e ...

What is the method of adding a child to the outerHTML of the parent element instead of within it?

Is there a way to use the outerHTML method on a parent element to append a child element so that the icons appear outside of the targeted element rather than inside it? The current code snippet shows the icons inside the box, but I want them to be placed o ...

Adjust the transparency of an image within an overlay when clicked on the overlay

Having an overlay on a Google map with two images contained within it, I am looking to adjust the opacity of the images when a user clicks on the overlay or on top of an image within the overlay. I attempted to utilize domlistener, but it did not yield the ...

What is the best way to connect a nested Vuex object to a Vue.js property within the Tiptap text editor?

I'm attempting to connect the nested Vuex state object to the editor property of the tiptap's editor-content component. The structure of the state is as follows: <template> <table :style="{ backgroundColor: element.options.ba ...

Exploring the Power of Multiple FindOne Queries in MongoDB

I have been working on expanding the data fields returned by our API. Currently, the API retrieves student information using the find method, and also includes some project details by retrieving the student info and using findOne to obtain information abou ...

Discovering the culprit causing a freeze on your page: Uncovering the tool or technique to identify the problematic

What is the best tool to identify resource-heavy or infinite loop JavaScript/jQuery scripts? I am currently experiencing issues with a specific template: When I open this page on Firefox 46.0.1, it freezes after a few minutes. I am having trouble pinpoin ...

Executing mathematical operations with floating point numbers using JavaScript in Python

I’m creating a Python program that interacts with a web application that I didn’t develop. There is some data that needs to be represented in my program which isn’t directly sent to the client by the server, but is instead calculated separately on bo ...

Adjust the color of text as you scroll

Could you provide guidance on changing the color of fixed texts in specific sections of my portfolio website? Unfortunately, I can't share my lengthy code here, but would greatly appreciate it if you could illustrate with examples. Here's a refer ...

Having trouble with Vue.js implementation of Bootstrap tab navigation?

I am currently working on a vue.js application that consists of 2 routed components. I recently attempted to integrate a bootstrap tab navigation into the first component, but unfortunately, the tab contents are not being properly displayed. <templat ...

When a pre-rendered page contains an element with the v-show attribute set to "false," it may flicker upon opening the page

Whenever I utilize the prerender-spa-plugin to prerender a page, a peculiar issue arises. A element (in this case, a modal) is invoked with a v-show="false" attribute by default. However, this modal consistently flickers when the page is opened, even tho ...

Whenever I include an onClick event to a div element, the entire webpage fails to display

Currently taking on the task of developing a seat booking website. I am encountering an issue with adding an event listener to a particular div element, which should trigger a function to store the value of the div. However, upon implementing the onClick e ...