Sending data through props to components that can only be accessed through specific routes

File for Router Configuration

import DomainAction from './components/domainaction/DomainAction.vue'
...
{ path: '/domainaction' , component: DomainAction },
...

Linking to Routes using Router Links

...
<router-link to="/domainaction" tag="li" class="list-group-item "class-active="active" exact > Domain Action</router-link>
...

Navigating to the domainaction Route from Other Routes

...

itemAction(action,data){
          if(action=='Suspend'){
            this.$router.push('/domainaction')
          }
        }
...

The Structure of My DomainAction Component

<template>
.......
</template>
<script>
export default {
  props:['data'],
  data(){
    return{
.........
</script>

I would like to pass data through the props in the itemAction function. Can someone please guide me on how to accomplish this? I am still learning Vue.js and may not have provided all the necessary details. Your help is much appreciated.

Answer №1

If you're looking to simply pass a property (a value) to the component, one way is to utilize data passing through the router's props: https://router.vuejs.org/guide/essentials/passing-props.html#function- mode. You can retrieve this passed data using this.$router within the component. Another option is to use Vuex for data passing. https://vuex.vuejs.org/ For communication between components not directly related as parent and child, 1 component can call another within it to pass values; otherwise, consider utilizing either data path via route or Vuex - the Vue status manager. Additionally, there's another approach discussed in relation to this question: Passing props to Vue.js components instantiated by Vue-router

Answer №2

It's important to note that utilizing Vuex is a good way to share data between components, as sosmii mentioned.

However, if you are interested in passing data through routes as parameters, you will need to make some adjustments in how you define the component routes. By using router params, you can pass props and then navigate to the route while adding parameters. Take a look at the example provided below.

Check out this related question for more insight: Passing props with programmatic navigation Vue.js

const DomainActionA = {
  props: ['dataProp'],
  template: '<div>A data: {{dataProp}}</div>'
 }
const DomainActionB = {
  props: ['dataProp'],
  template: '<div>B data: {{dataProp}}</div>'
 }

const routes = [
  {
    path: '/DomainActionA/:dataProp',
    name: 'domainA',
    component: DomainActionA,
    props: true },
  { 
    path: '/DomainActionB/:dataProp',
    name: 'domainB',
    component: DomainActionB,
    props: true
   }
]

const router = new VueRouter({
  routes
})

const app = new Vue({
  router,
  methods: {
    goToA() {
       this.$router.push({name: 'domainA', params: {dataProp: "blah"}})
    },
    goToB() {
       this.$router.push({name: 'domainB', params: {dataProp: "bleh"}})
    }
  }
}).$mount('#app')
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
  <h1>Hello Router!</h1>
  <div>
   <button @click="goToA()">Go A with params: { data: "blah" }</button>
   <button @click="goToB()">Go B with params: { data: "bleh" }</button>
  </div>
  <div>
    <h2>router view</h2>
    <router-view></router-view>
  </div>
</div>

Answer №3

Consider implementing Vuex for better state management

Props are primarily intended to transfer data from a parent component to a child component. Therefore, it is not recommended to use props for sharing data between different pages.

An appropriate use case for props can be demonstrated below:
parent.vue

<child-component :data="data">
<child-component :data="anotherData">

If you need to share variables across multiple pages, it is advisable to utilize Vuex (store pattern) instead.

For more information, please refer to a similar question:

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

Running npm commands, such as create-react-app, without an internet connection can be a

Currently, I am working in an offline environment without access to the internet. My system has node JS installed. However, whenever I attempt to execute the npm create-react-app command, I encounter an error. Is there a workaround that would allow me to ...

Warning: Knex was unable to acquire a connection due to a timeout, resulting in an UnhandledPromiseRejectionWarning

I'm having trouble connecting my Telegram bot to the database using knex. I am working with MySQL, and I have already created the database and tables which are visible on the /phpMyAdmin page. The credentials used for accessing the database in my code ...

Exploring the benefits of looping with node.js require()

Currently, I have defined the required files as shown below. constantPath = './config/file/' fileAA = require(path.resolve(constantPath + 'A-A')), fileBB = require(path.resolve(constantPath + 'B-B')), fileCC = require(path.r ...

rearrangement of characters in a string (javascript)

I am currently working on a game where users have to guess a word by selecting the right symbol from the alphabet. When the user guesses correctly, the code is supposed to replace all placeholders with the correct character, but in the wrong order. var se ...

Watching for changes in a callback function - Angular 2

I'm currently working on implementing a callback function within a service class that needs to send data back to the component class. ChatComponent.ts export class ChatComponent implements OnInit { constructor( public _chatService : ChatService) ...

Crafting a robust and secure password using Yup and Formik while receiving personalized error notifications

My Password Validation Dilemma I'm in the process of developing a password field that can assess the strength of the input provided. In a different response, I came across a regex that I could utilize to validate whether the input meets specific crit ...

In JavaScript, when a div element contains an iframe, the click event will not trigger on the div

Check out this sample HTML markup: <div> <iframe></iframe> </div> The iframe is set to fill the outer div. I've added an event handler to the div click event: div.addEventListener("click", function () { console.log( ...

There seems to be an issue with the border displaying correctly within the div element

I am currently working on developing a tag input system, but I am encountering some CSS issues. What I am aiming for is to have a green border that surrounds and contains the 2 divs inside it, however, this is not happening as expected. You can see the fi ...

Open boxes with walls that don't create shadows

Currently, I am facing an issue with an open-sided box created using MeshStandardMaterial and BoxGeometry. I have configured the box to cast and receive shadows, but it is not behaving as expected. I anticipated the interior of the box to darken when the p ...

Tips for ensuring elements within a modal receive immediate focus when opened in Angular 2

I am relatively new to Angular JS and I am encountering some challenges with implementing a directive in Angular 2 that can manage focusing on the modal when it is opened by clicking a button. There have been similar queries in the past, with solutions pr ...

Understanding the Execution of Asynchronous Code

I've been grappling with this problem for a while now, but I just can't seem to find the solution. That's why I'm reaching out for your expertise. Consider the example below: const async = require('async') var counter = 0 v ...

Creating an HTML design with divs: a trio of pictures that adjusts in size to match the viewport (sl

As a newcomer to HTML and CSS, I find myself nearing completion of my website, with the final obstacle being an image slider in the background. The Challenge: The images are not perfectly centered within the viewport. Specifically, the first image needs ...

How can I swap out the text within an anchor tag using jQuery?

I am working with the following HTML structure: <div class="event tiny"> <a href="/whatever">Something</a> </div> My goal is to change the text of this link to "Anything" … However, when I try the following code: $('. ...

What is the best way to change the status of a disabled bootstrap toggle switch?

I'm working with a read-only bootstrap toggle that is meant to show the current state of a system (either enabled or disabled). The goal is for it to update every time the getCall() function is called. However, even though the console logs the correct ...

Can you provide instructions on how to use JavaScript to click and hold a button for a specific duration?

Is it possible to use jQuery to create a button that, when guest button number 1 is clicked, will automatically click and hold down button number 2 for about 3 seconds? I have tried using the mousedown() and click(), but they only register a click, not a ...

Struggling with the compilation of this Typescript code

Encountering a compile error: error TS2339: Property 'waitForElementVisible' does not exist on type 'signinPage' SigninPage code snippet: export class signinPage{ constructor(){ emailInput: { selector: 'input[type ...

What is the best way to conceal content within a URL while still transmitting it to the server using node.js and express?

I have been trying to figure out how to hide certain content from the URL, but still need to send that information to the server in my Express app. So far, I haven't found any solutions that work. For example, if I have a URL like www.abc.com/viewblo ...

Creating a large JSON file (4 GB) using Node.js

I am facing a challenge with handling a large json object (generated using the espree JavaScript parser, containing an array of objects). I have been trying to write it to a .json file, but every attempt fails due to memory allocation issues (even though m ...

Component fails to trigger @click handler

.vue component <template> <div class="modal"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> Loading Files </div> < ...

Struggling to connect with PouchDB within my HTML-based Web application

I am looking to integrate pouchDB into my WebApp so that upon clicking a button, the data from a JSON file will be saved to pouchDB. In the initial stage in my index.html, I included the following: <script type="module" src="pouchdb/packa ...