Dynamically populate content on render in Vue.js based on the vue.router parameters

Can anyone help me understand why I'm receiving unexpected results? I am using v2 vue.js.

In my project, I have a single file component for a Vue component. The component is supposed to render data imported from "excerciseModules" in JSON format.

The rendering logic is dynamic and based on the URL path, it should determine which data to fetch from the JSON and display it on the page. However, the rendering happens before this logic, and I can't figure out why. I have implemented similar views successfully in the past, so I'm confused about what's different here.

I decided to handle the data loading in one view component without creating multiple routes. But currently, the data loads empty initially with the placeholder name "TrainingModules," and then loaded with old data on subsequent renders.

For example, when the URL path is "/module1", the page loads empty initially.

Then, if the next path is "/module2", the page still shows module 1.

And when the path is changed back to "/module1", only then does module 2 appear.

//My route
{
    path: '/excercises/:type',
    name: 'excercises',
    props: {},
    component: () => import( /* webpackChunkName: "about" */ '../views/training/Excercises.vue')
}
<template>
<div class="relatedTraining">
    <div class="white section">
        <div class="row">
            <div class="col s12 l3" v-for="(item, index) in trainingModules" :key="index">
                <div class="card">
                    <div class="card-content">
                        <span class="card-title"> {{ item.title }}</span>
                        <p>{{ item.excercise }}</p>
                    </div>
                    <div class="card-action">
                        <router-link class="" to="/Grip">Start</router-link>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</template>

<script>
    console.log('script');
    let trainingModules; //when initialized this is empty, but I would expect it to not be when the vue is rendered due to the beforeMount() in the component options. What gives?
/* eslint-disable */
let init = (params) => {
    console.log('init');
    console.log(trainingModules);
    trainingModules = excerciseModules[params.type];
   

    //return trainingModules
    
}
import { getRandom, randomImage } from '../../js/functions';
import { excerciseModules } from '../excercises/excercises_content.js'; //placeholder for JSON
export default {
    name: 'excercises',
    components: {
    },
    props: {
    },
    methods: {
        getRandom,
        randomImage,
        init
    },
    data() {
        return {
            trainingModules,
        }
    },
    beforeMount(){
        console.log('before mount');
        init(this.$route.params);
    },
    updated(){
        console.log('updated');
        
    },
    mounted() {
        
        console.log('mounted');
        //console.log(trainingModules);
    }
}

</script>


Answer №1

Unfortunately, without seeing your specific code, I can't pinpoint why it's not working. However, I can provide you with a basic example that demonstrates the functionality you're trying to achieve.

First and foremost, make sure your vue-router is set up correctly. Here's an example configuration:

export default new Router({
  mode: "history",

  routes: [
    {
      path: "/",
      component: Hello
    },
    {
      path: "/dynamic/:type",
      component: DynamicParam,
      props: true
    }
  ]
});

In this setup, there's a route configured with dynamic route matching using a parameter named `type`. By prefixing the parameter in the path with `:` we tell vue-router to treat it as a route parameter. Additionally, setting `props: true` allows the value of the slug to be passed as a prop to the DynamicParam component.

The DynamicParam component structure is as follows:

<template>
  <div>
    <ul>
      <li v-for="t in things" :key="t">{{ t }}</li>
    </ul>
  </div>
</template>

<script>
const collectionOfThings = {
  a: ["a1", "a2", "a3"],
  b: ["b1", "b2"],
  c: [],
};

export default {
  props: ["type"],
  data() {
    return {
      things: [],
    };
  },
  watch: {
    type: {
      handler(t) {
        this.things = collectionOfThings[t];
      },
      immediate: true,
    },
  },
};
</script>

This component utilizes a watcher to react to changes in the URL parameter. When the slug changes, the corresponding prop gets updated accordingly. You can use this mechanism to fetch real data from sources like APIs or databases.

For a working demonstration, check out this codesandbox example: https://codesandbox.io/s/vue-routing-example-forked-zesye

Remember, presenting a minimal reproducible example when seeking help can greatly aid others in understanding and assisting with issues. Learn more about creating such examples here:

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

Execute the laravel {{action(Controller@method}} by sending a parameter from a vue.js array

Within my view created using Blade templates, I have a link with an href attribute that directly calls a Controller method. Here is an example: <a id="@{{user.id}}" href="{{action('Controller@method')}}">>update</a> Everything wo ...

Accessing a file url with Firefox using protractor

I am currently facing a challenge with Protractor as I try to access an HTML file as a website using it. Whenever I attempt to do so, I encounter an error from Protractor stating: Failed: Access to 'file:///C:/filelocation/index.html' from s ...

Experience seamless slide transitions with the react-slick carousel using scroll events in React JS and JavaScript

Currently utilizing the carousel library found at: react-slick I am interested in enabling mouse scroll functionality to navigate through each slide. The idea is to scroll up to progress forward and scroll down to go backward. Came across a relevant exa ...

Maximizing the potential of Angular forms through native FormData

Currently, I am revisiting an older project that still uses traditional methods for form submission. The HTML includes a form element with defined method and action. My goal is to submit the form in the old-fashioned way using the action attribute to post ...

The jQuery($) function cannot be accessed within the module file

I have been utilizing webpack to consolidate my code. The following excerpt is from my main.js file where I am including jQuery. main.js var $ = global.jQuery = require('jquery'); $('someSelector').on('rest of the code.& ...

Vue Js does not include images in the dist directory when the build process is completed

In my VueJs 3 project, I am working with a list of PNG images stored in the src/assets/pngs/ directory. Within my Vue component, I use a For loop to dynamically create the list by setting the image name as the source for the img tag. This implementation wo ...

"Experiencing difficulties deploying Firebase functions - Encountering an error message stating 'Cannot read property 'firebase-admin' of

I'm currently facing an issue during the deployment of my Firebase functions and I am seeking assistance to resolve it. While the deployment itself appears to be successful, I keep encountering the following error: Cannot read property 'firebas ...

"Enhance Your WordPress Website with the Power of jQuery

I have been developing a unique Wordpress plugin that incorporates a grid loading effect using jQuery. The script I have implemented is as follows: <script type="text/javascript"> new GridScrollFx( document.getElementById( 'grid' ), { ...

Utilizing AngularJS to make an API call with $http method and handling a

I am attempting to make a call to my webservice using "$http". When I use "$ajax", it works fine. Here is an example of jQuery $Ajax working correctly: $.ajax({ type: "Get", crossDomain: true, contentType: "application/json; chars ...

What is the best way to store information in my express server using Angular?

After spending several hours on this issue, I am feeling stuck. Initially dealing with a CORS problem, I managed to solve it. However, my goal is to utilize $resource without creating a custom post method. My API follows RESTful standards where POST /artis ...

Invoking Javascript Functions using their names

Suppose I have the following element on my page... <span data-function="DoSomething">Click</span> ... and then add the following to my page header... $(document).ready(function() { $('[data-function]').each(function() { ...

Observing the CSS class of an input element during async validation does not yield the desired results

Recently, I implemented a bootstrap directive that monitors all the input elements on a form and updates the CSS of its parent div to display validation errors in a Bootstrap-friendly manner. The directive checks for the presence of the ng-invalid class in ...

Error encountered while rendering content in an Angular template

I'm currently integrating ngx-carousel into my application. Interestingly, the carousel works perfectly when I manually input the data. However, when trying to fetch the data from the server, it fails to work as expected. Take a look at my code snip ...

Displaying the servlet response within an iframe

This is the content of Content.jsp <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> &l ...

Adjust webpage display with JavaScript

Utilizing the mobile-first approach of Zurb Foundation, I successfully created a responsive design. However, my client now requires a direct link labeled "View desktop version" in the footer for when the website is accessed on mobile devices or tablets. T ...

Using AJAX autocomplete with Sys.Serialization.JavaScriptSerializer

I implemented an ajax autocomplete feature in ASP.NET where a method from a web service is called to fetch postal codes. public string[] GetNames(string prefixText, int count, String contextKey) { prefixText = prefixText.Trim(); XmlNodeList list; ...

Utilizing AngularJS to iterate over a single extensive unordered list

In my current Angular app, the JSON structure is as follows: 0: Object $$hashKey: "004" Date: "2014-04-17" Items: Array[3] 1: Object $$hashKey: "005" Date: "2014-04-18" Items: Array[3] 2: Object $$hashKey: "006" ...

Updating the styles of React Native components using stylesheets

I've created a unique React component with the following structure: import { StyleSheet } from 'react-native'; import { Input, Item } from 'native-base'; import Icon from 'react-native-vector-icons/FontAwesome'; import { ...

What is the best way to specify option values for selection in AngularJS?

...while still maintaining the model bindings? I currently have a select menu set up like this: <select class="form-control" ng-model="activeTask" ng-options="task.title for task in tasks"> </select> When an option is selected, it displays s ...

How can I display milliseconds from a date in Angular2+?

I recently encountered an issue while working with a custom pipe that was used to display time. I attempted to modify it so that it could also show milliseconds: {{log.LogDate|jsonDate|date:'dd.MM.yyyy &nbsp; HH:mm:ss.sss'}} Here is the cod ...