Transferring a dynamic property from the $root instance to a child component through vue-router

How can VueJS pass a prop to a child component from the $root view instance while using vue-router?

$root instance:

const router = new VueRouter({
    routes: [{
        path: "/dashboard",
        component: () => import("./User/Dashboard.vue" /* webpackChunkName: "js/components/user/Dashboard" */ )
    }]
});

var app = new Vue({
    el: '#app',
    router,
    data: () => ({
        passedProp
    }), 
});

Laravel Layout using :

@section('content')
    <transition name="slide">
        <router-view></router-view>
    </transition>
@endsection

Child Component served by vue-router:

<script>
export default {
    props: [
        'clearFormProp'
    ]
}
</script>

In the vue-router documentation, there is a way to pass a prop via the url, however, this method makes the prop stateless and does not retain reactivity. It only updates the prop on page refresh.

Passing a static prop presents the same issue.

Is there a way to pass a prop to the child component while still maintaining reactivity for the prop?

Answer №1

Send properties to <router-view/> and retrieve them in the child components

<router-view :dataProp="localData"></router-view>

and in the designated component:

<template>
  <h1>
    {{ dataProp }}
  </h1>
</template>
<script>
 export default{
   props:{
     dataProp: Object
   }
 }
</script>

Answer №2

This solution employs the State Pattern to tackle the issue at hand.

Imagine a basic counter application, featuring a text that showcases the current value and a button that increases it each time the user clicks on it.

The state is extracted into a constant:

const counter = {
    value: 0
}

export { counter };

You can then import it in the child component and modify it directly using Vue:

<template>
    <div>
        Counter value from child:
        {{ counter.value }}
    </div>
    <div>
        <button type="button" @click="() => counter.value++">Increment from child</button>
    </div>
</template>

<script>
import { counter }  from "/src/counter.js";

export default {
    data: () => ({ counter })
}
</script>

In the root component, you can perform the same actions:

<template>
    <div>
        Counter value from root:
        {{ counter.value }}
    </div>
    <div>
        <button type="button" @click="() => counter.value++">Increment from root</button>
    </div>

    <ChildComponent />
</template>


<script>
import ChildComponent from './components/ChildComponent.vue'
import { counter }  from "/src/counter.js";

export default {
  name: 'App',
  data: () => ({ counter }),
  components: {
    ChildComponent
  }
}
</script>

Refer to the image below to witness how the example functions:

https://i.sstatic.net/FOGRg.gif

Note: This approach only works because the two components are mutating the same object and triggering events to refresh themselves. If you increment the counter value outside a component, you will not observe the refresh, which can be addressed with Vuex.

Moreover, if your application frequently deals with controlling data across various components, I also recommend utilizing Vuex.

Vuex is a state management pattern + library for Vue.js applications. It acts as a centralized store for all components in an application, ensuring that the state can only be modified predictably.

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

Alignment of content layout across two wrapper elements

My goal is to achieve a specific layout where each pair of cards in a two-column layout is aligned based on the card with the largest content. Both cards share the same content layout and CSS. If you have any ideas or implementations that could help me ac ...

Implementing dynamic image insertion on click using a knockout observable

I'm utilizing an API to retrieve images, and I need it to initially load 10 images. When a button is clicked, it should add another 10 images. This is how I set it up: Defining the observable for the image amount: public imageAmount: KnockoutObserva ...

Issue with mobile device view: BS custom dropdown toggle not functioning

Built a Bootstrap dropdown navbar with custom jQuery & CSS, but facing an issue with toggling submenu in Mobile devices. See the code snippet below: $('.dropdown').click(function() { $(this).children('.dm-lv1').toggleClass('s ...

Create a small circle in the bottom left corner with a constrained size

I'm trying to create a circle at the top of the screen on mobile, similar to the image below. The circle should take up a percentage of space, with the rest of the content appearing against a blue background as shown in the image. However, I'm h ...

Utilizing arrays to dynamically alter the text color of specific words in an input field

Currently, I am in the process of working on a JSFiddle and find myself a bit puzzled by a certain aspect. Within my project, I have an input box named myTextField which contains a random paragraph. Additionally, there is a button that triggers my change f ...

Exploring Object Literal Lookups in Typescript

Check out this minimal reproducible example of the issue I've created an object literal: const map = (filter: Filter) => { return { [Filter.USERS]: { fetch: async () => getUsers(), set: setUsers, }, [Filter.FIRMS]: { ...

Sort firebase information by chronological order based on timestamp

I'm currently working on sorting track IDs from firebase based on their timestamp (createdAt). The function is functioning correctly, but the ordering doesn't seem to work as expected. I'm not sure where the issue lies. Any assistance or sug ...

The script fails to work correctly when displaying the data

Last night, I finally cracked the code on how to transfer data from my form on the index page to the content page, and then display the results inside the content div back on the index page. However, a new challenge has emerged. My Javascript function (re ...

Finding the midpoint of SVG paths and VML shapes

I'm currently experimenting with: My main focus is on obtaining the center points of different countries (to accurately place markers on each country). I've encountered some challenges in achieving this and have attempted various methods, such ...

Evaluate easy Ajax- Success Function

Today, I am experimenting with testing a basic Ajax request using Jasmine: var Card = { single : function(params){ $.ajax({ dataType: "json", headers: {"X-TOKEN": TOKEN}, url: SERVER, success: fu ...

Translating from a higher-level programming language to a lower-level programming language

Is compilation effectively the transformation of high-level programming languages (HLL) into machine code or low-level language? If so, why is TypeScript (a HLL) compiled to JavaScript (also a HLL) instead of being compiled to a low-level language? ...

Accessing data from an array using onClick in a React component

I have an array.map of buttons that cycles through API data. When a button is clicked, I want to take that specific button's data and store it in local storage. I've been searching on Google but can't figure out how to do this. Any ideas? {t ...

Retrieving an image from an input file and setting it as the background of a div element

I am currently developing a whack the mole game using Vanilla JS, and I'm attempting to allow players to choose their own target by uploading an image file. However, despite days of searching for a solution, I have not been successful. HTML: <inpu ...

I desire to alter the description of an item within a separate div, specifically in a bootstrap

I used the map method to render all the images. However, I need a way to track the current image index so that I can change the item description located in another div. Alternatively, if you have any other solutions, please let me know. App.js : import Ca ...

Storing various property values in Vuex stateorManaging multiple property

Here is a demo link that I would like to share: https://codepen.io/Albvadi/pen/abdVZxO In the payload, I am trying to pass the title and class but only the class is being recognized. When I attempt to change the @click event to pass an object, the JavaSc ...

Is it possible to verify the presence of an ID with jQuery?

Is it possible to check for the existence of the id 'input-name' before assigning a value to the variable name using a line of code similar to this: var name = $('#input-name').attr("value"); In case the id 'input-name' does ...

Is it necessary to include @types/ before each dependency in react native?

I am interested in converting my current react native application to use typescript. The instructions mention uninstalling existing dependencies and adding new ones, like so: yarn add --dev @types/jest @types/react @types/react-native @types/react-test- ...

Exploring the emission of Vue 3 with the Options API through typing

Is there a way to declare emits in Vue 3 Options API similar to the Composition API approach? Based on the Composition API documentation: (docs) <script setup lang="ts"> // type-based const emit = defineEmits<{ (e: 'change', ...

Adjusting the Transparency of the Background in a Pop-Up

I am experiencing an issue with my popup where I want the background to be transparent. However, when I set the opacity in CSS to 0.5 or less, the text also becomes transparent and very dark. How can I achieve a background with 50% opacity while keeping th ...