Using Vue.js to send various data to child components through the router

I am facing a dilemma with the nested router setup in my Vue app.

Here is a snippet from my router/index.js:

{
    path: "/parent",
    name: "Parent",
    component: () =>
      import(/* webpackChunkName: "parent" */ "../views/Parent.vue"),

    children: [{
      path: ':id',
      name: 'ChildOne',
      components: {
        nestedview: () =>
          import(/* webpackChunkName: "child-one" */ "../views/ChildOne.vue"),
      }
    },
    {
      path: "child-two",
      name: "ChildTwo",
      components: {
        nestedview: () =>
          import(/* webpackChunkName: "child-two" */ "../views/ChildTwo.vue"),
      }
    }]
  },

In the Parent component template (using pug syntax):

  router-view(
    name="nestedview",
    :functionOne="functionOne",
    :functionTwo="functionTwo",
    :functionThree="functionThree",
  )

The issue arises when I need to pass specific functions as props to Child components. While it works fine for ChildOne, where all three functions are passed correctly, in ChildTwo only functionOne is received properly while the other two show up as strange parameters in the source code.

My question is, how can I ensure that different data is passed as props from the Parent component to these Child components rendered through the nested router mechanism?

Answer №1

v-bind automatically binds an attribute if a property is not found.

To address this issue, one solution is to utilize the v-bind with the .prop modifier. This ensures that the binding only attempts to set the component prop if it actually exists (otherwise, nothing will be bound):

router-view(
  name="nestedview",
  :functionOne.prop="functionOne",
  :functionTwo.prop="functionTwo",
  :functionThree.prop="functionThree",
)

Check out this demo for more information.

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

Guide on creating CSS for webkit scrollbar through the use of Javascript

I have a div named 'dynamic' with text inside, and I am applying styling to it using javascript. var styleElement = document.createElement("style"); styleElement.appendChild(document.createTextNode("#dynamic { color: red; }")); document.getEleme ...

Is it possible to avoid sending multiple $http requests in Angular? Are there more efficient methods available?

I have developed a rather intricate method for retrieving resources using $http. This method returns a promise and first checks my local cache to see if the resources are already available. If they are, it will return the cached data; if not, it will make ...

A collection of JSON objects retrieved from a fetch request

When I send a fetch request to an API, I receive a response that is an array of JSON objects, for example: [ {"key":"val", "k2":"v2"}, {"k3":"v3", "k4":"v4"} ] Currently, I am handling this by using response => response.text() Is there a more efficie ...

Execute sequential animations on numerous elements without using timeouts

I'm currently working on developing a code learning application that allows users to write code for creating games and animations, similar to scratch but not block-based. I've provided users with a set of commands that they can use in any order t ...

Access denied, can forever.js be used as a bash script?

After some troubleshooting, I managed to set up a bash script that allows me to run indefinitely. In FileZilla, I went ahead and modified the permissions for /usr/local/lib/node_modules/forever to 777. post-receive bash script #!/bin/sh git --work-tree=/ ...

Switching class upon clicking in Vue3

I'm trying to toggle a class on click, but for some reason it's not working as expected. <script setup> import { ref } from "vue"; let isOpen = ref(false); const toggleClass = () => { isOpen = !isOpen; console.log(isOpen) ...

Why does my JSON variable contain "type" and "data" values instead of something else?

After using JSON.stringify() on my object to save it to a file, I noticed that one of the parameters does not have the expected string value assigned. Instead, it has a "type" and "data". Code: fs.writeFileSync('myjson.json', JSON.stringify(myjs ...

Decoding JSON object from the "string" using JSON.parse function

I am attempting to send a JSON string from a PHP controller to a twig template using the following method: $data['dist_result'] = json_encode($distribution_service->setDistribution($ids,$distribution)); $this->display('backend/shipmen ...

javascript pull data from an array

As a novice in HTML and JavaScript, I have a brief code snippet that embeds multiple audio files. I am utilizing a loop and would like to utilize strings from an ARRAY as the sources for the WAV files (rather than just "file1.wav"). Thank you. <!DOCT ...

Managing several items within one function

I am working with a json file that contains similar data sets but different objects. { "AP": [{ "name": "Autogen Program" }, { "status": "Completed" }, { "start": "2014-05-05" }, { ...

Vue JS projects do not support Tailwind styles

Just getting started with vue js and wanted to create a cool little demonstration. I decided to incorporate tailwindcss into my new project. Here's how I set up the project: vue create vue-tailwind-template Then, I added tailwind using the following ...

Display a hidden form field in Rails depending on the object's value

As a programmer learning Ruby on Rails without much knowledge of Javascript, I faced a problem with a form that creates an object called Unit. This Unit model is related to Category which in turn is related to Product. The issue was that while selecting a ...

Grouping various event listeners within a v-for loop

My Desired Outcome In my Vue component, I am displaying a list of actions using v-for. Each action should have a corresponding @click event handler that triggers the action method within the component. I need help declaring these actions in my data() fun ...

How to include images in a PDF using jspdf without encountering issues with Adobe Reader?

For a project I'm working on, I've integrated jspdf to convert some charts into a PDF. The framework I'm using is angularjs 1.5.6, and the charts are created with chart.js. The HTML snippet for the charts looks like this: <div name="char ...

Send form data without reloading the page and connect it to a JavaScript script

I've designed a system that reveals values based on a specific input selection. Below is the main form where users can enter model numbers and press enter: <form> <input type="text" name="ModNum" id="ModelNumber" pattern="^PIV13RT[23]?$" ...

When incorporating pinia with Vue, encountering an error with the decorator that says "Error: Unable to access 'useCoreStore' before initialization" may happen

While implementing the vue-facing decorator in my current project, I encountered an issue with setting up pinia. The structure of my component resembles the example provided here: I have verified that decorators like @Setup are functioning correctly, ind ...

Utilizing React for handling data exchange between child and parent components

I am still learning about React and material-ui, and I am exploring how to pass data from a child component to a parent component to update the parent state. Currently, when I try to update the state with a new date, it is being logged in the console but t ...

How can a border be applied to a table created with React components?

I have been utilizing the following react component from https://www.npmjs.com/package/react-sticky-table Is there a method to incorporate a border around this component? const Row = require("react-sticky-table").Row; <Row style={{ border: 3, borderco ...

Challenges with ExpressJS 4 middleware

Trying to grasp the concept of middleware in ExpressJS 4 has been quite a challenge for me. As far as I understand, middleware are applied based on the order they are declared and can be "bound" at different levels. My current focus is on binding a middl ...

Retrieving ID of an element to be animated with jQuery

I have a sprite image that changes background position when hovered over, and while it's currently working, I'm looking for a more efficient way to achieve this. I need to apply this effect to several images and am exploring ways to avoid duplica ...