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

Harvesting the local image file

Currently, I have implemented a form that allows users to upload images and crop them. The process flow has been established as follows: 1. User uploads the image 2. Server processes the image and sends it back to the browser 3. User crops the image a ...

Determine line-height and adjust positions using JavaScript in the Chrome browser

I am creating a basic text reading application with a line to aid in easy reading. The functionality involves using the up and down arrow keys on the keyboard to adjust the position of a red line based on the line-height property. This is accomplished thr ...

Unable to trigger Vuejs click event when using v-if condition

I've encountered a strange issue. I'm attempting to trigger a method when an element is clicked in a v-for loop, but it doesn't seem to work when using v-if or v-show. Here's a sample of my HTML code: <div class="chosen-drop custom ...

Ways to retrieve information from a URL using the .get() method in a secure HTTPS connection

As I work on handling user input from a form using node.js, express, and bodyParser, I encounter an issue. Even after using console.log(req.body), the output is {}. This is puzzling as there is data in the URL when the form is submitted successfully at htt ...

When attempting to modify the state in a parent component from a child using the composition API in Vue 3, the error "this.$emit() is not a

//Main component <template> <childComponent @onChangeData='updateData' /> </template> <script> setup() { const state = reactive({ data: 'example' }); function updateData(newValue){ s ...

Ensuring correct association of values to avoid redundancies

There are 5 fields available for users to fill out on this form: Leave Code, From Date, Input Time1, To Date, and Input Time2. These variables are declared as a dates object in the .ts file, as shown below. interface Supervisor { name: string; code: s ...

Adjust the Placement of Images in Relation to Mouse Movements

Is there a way to creatively animate the positions of images or background images based on mouse movement? Let's take Github, for instance: https://github.com/thispagedoesntexist The 404 page on Github is truly impressive. I aim to captivate my use ...

Arranging the data in the table by alternating rows using Datatables

I need to organize my data in a way that includes an additional row for descriptive information, but this particular row should not be sorted. It is crucial for understanding the rest of the data, so hiding or showing it is not an option. Is it possible t ...

"How can you enhance the performance of JavaScript and CSS in a Chrome Extension without using exclude_matches/globs or excluding domains

I have been in the process of creating a Chrome Extension, and unfortunately, when I tried to make it work on specific URLs, I encountered an issue. While Chrome has options like exclude_matches and exclude_globs for this purpose, there seems to be a bug i ...

Exploring the beauty of ASCII art on a webpage

Having trouble displaying ASCII art on my website using a JavaScript function, the output is not as expected... This is how it should appear: And here is the code I am trying to implement for this purpose: function log( text ) { $log = $('#log&ap ...

Bootstrap-vue throws an error when Vue is not defined

Recently, I integrated bootstrap-vue into my Vue.js project by running the command yarn add bootstrap-vue bootstrap axios. Here is a snippet of my code: https://i.stack.imgur.com/oTBxn.png Another part of the code can be found here: https://i.stack.imgur ...

Unspecified origins of Js in Chrome Extension

console.log(chrome.runtime.sendMessage({from:"script2",message:"hello!"})); However, attempting to send the message from a background script to a content script is proving to be unsuccessful. https://i.stack.imgur.com/ERgJB.png ...

Making JavaScript Code More Efficient with VueJS and VUEX

Keeping my Javascript code clean and concise is a top priority for me. I always strive to condense my code so that it remains clutter-free without sacrificing functionality. Take a look at my vuex-mutation code below: editEvent(state) { if (state.for ...

Undefined is the value assigned to Javascript Dot Notation

When using dot notation to access objects with a '.', I am encountering an issue that I cannot seem to figure out. The success function in my jQuery $.ajax function looks like this: success: function(data){ console.log('data = ' + da ...

Navigating the route with quickness

Upon accessing the localhost, I encountered an issue with the code snippet below: When I try to access it, I receive an error message saying "Cannot GET /". var express = require('express'); var router = express.Router(); /* GET home page. */ r ...

Using Jquery to make an Ajax request to an Asp.net Web Method

My current approach involves using a jquery method to transmit only the member identification # from the client side to the server side. On the server side, I have a traditional Web Method in place to receive the data and execute SQL queries accordingly. ...

Is there a way to hide the <v-otp-input> field in a Vue.js application?

For more information, please visit https://www.npmjs.com/package/@bachdgvn/vue-otp-input <script> export default { name: 'App', methods: { handleOnComplete(value) { console.log('OTP completed: ', value); } ...

Calculating the quantity of elements within a jQuery array

A JQuery array is proving to be quite problematic. Here's what it looks like, [125, "321", "kar", 125, "sho", "sho", 12, 125, "32", 32] Unfortunately, there are duplicates present in this array. My goal is to obtain the count of each unique element ...

Retrieving radio button value in Angular 2

Currently, I am attempting to retrieve the radio button value in an Angular 2 project. The radio buttons are defined in index.html as: <input type="radio" id="options1" name="function" value="create"> <input type="radio" id="options2" name="func ...

Using React hook form to create a Field Array within a Dialog component in Material UI

I have a form with custom fields added via Field Array from react-hook-form, and everything is functioning properly. However, I recently implemented drag and drop functionality for the property items to allow reordering them. Due to the large number of fie ...