Sharing values across all routes using router-view

I have data for currency and I would like to share this data with all views without having to call the same function in each view.

My solution was to call the function in App.vue (my main view), but I am struggling to figure out how to pass it along with router-view.

Code

HTML

<template>
  <el-container :is="layout">
    <transition name="fade">
      <router-view id="content" :key="$route.fullPath"></router-view>
    </transition>
  </el-container>
</template>

Script

export default {
    data() {
      return {
        isCollapse: true,
        user: '',
        type: '',
        site_name: process.env.MIX_APP_NAME
      }
    },
    created () {
      this.getCurrency()
    },
    methods: {
      getCurrency() {
        axios
        .get('/api/currencyDefault')
        .then(response => {
          this.currency = response.data.data
        })
        .catch(function (error) {
          console.log('error', error);
        });
      },
    }
}

Any insights on how to solve this?

Answer №1

If you want to transfer that currency to the router view, you can achieve it by following these steps:

    <template>
      <el-container :is="layout">
        <transition name="fade">
           <router-view :currency="currency"id="content" :key="$route.fullPath"></router-view>
        </transition>
      </el-container>
    </template>

export default {
    data() {
        return {
            isCollapse: true,
            user: '',
            type: '',
            site_name: process.env.MIX_APP_NAME
        }
    },
    created () {
        this.getCurrency()
    },
    methods: {
        getCurrency() {
            axios
            .get('/api/currencyDefault')
            .then(response => {
                this.currency = response.data.data
            })
            .catch(function (error) {
                console.log('error', error);
            });
        },
    }
}

Now, in your other view, you can access it using props like this:

export default {
    props:['currency']
}

However, a downside of this method is that if you have nested child components and still need to access the currency data, you'll end up passing props multiple times to different router views which can become cumbersome. My suggestion would be to use Vuex instead. This way, the currency data will be accessible across all your views.

Refer to the documentation here for more information on Vuex.

Answer №2

If you want to transfer props to the router view and have them passed down to the child component, there is a helpful solution on Stack Overflow that addresses this issue: How to pass data to a router-view in Vue.js

<router-view :currency="currency"></router-view>

It's essential to note one potential problem with your code - by setting this.currency in your API call, you're inadvertently overwriting another method with the same name. It might be beneficial to consider renaming your method to getCurrency.

methods: {
  getCurrency () {
    axios
    .get('/api/currencyDefault')
    .then(response => {
      this.currency = response.data.data
    })
    .catch(function (error) {
      console.log('error', error);
    });
  },
}

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 several setInterval functions on a Node server

My application is a gaming platform that challenges users to complete tasks within a 30-minute timeframe using a node backend. Whenever a user initiates a game, a unique setInterval function activates on the server side. This timer counts down for 30 minu ...

What is the reason AJAX does not prevent page from refreshing?

Can anyone offer some guidance on using AJAX in Django? I'm attempting to create a basic form with two inputs and send the data to my Python backend without refreshing the page. Below is the AJAX code I am using: <script type="text/javascript& ...

The issue of uploading files using Ajax in CodeIgniter and Jquery is causing problems

I am attempting to implement a file upload using Ajax in CodeIgniter, but it seems like my Jquery code is not properly retrieving the data from the form even though the file appears to be included in the POST message. Below is my controller: public funct ...

Is there a way to expand a pie chart into a new pie chart with PHP and Javascript?

I need help finding a code that can expand a pie chart into another pie chart. The original pie chart appears too congested with numerous entries when it first loads. I have only come across tutorials for accomplishing this in Excel online. Can someone a ...

How to eliminate spacing between photos in a flexbox layout

[Unique] Find the Solution Image inside div has extra space below the image My design showcases various images of different sizes in multiple rows. See an example here. Despite my efforts, there are noticeable gaps between the rows that I can't seem ...

Tips for reducing unwanted messages on a form

My website features a basic registration form where users can sign up for a newsletter by entering their email address. I am concerned about potential spammers flooding my system with fake email addresses. Does anyone have any suggestions on how to preven ...

The File Reader just informed me that parameter 1 is not in the form of a blob

When working with a file input in my React component, I keep encountering an error with the FileReader. Here's the specific error message: Uncaught TypeError: Failed to execute 'readAsDataURL' on 'FileReader': parameter 1 is not o ...

What is the best way to incorporate a loading icon onto a webpage that exclusively runs JavaScript functions?

I frequently use Ajax load icons to indicate progress during ajax requests. Is there a way to achieve the same result using regular JavaScript? For instance: $('button').on('click', function(){ showLoadingIcon(); lengthyProces ...

Recently added classes are not exhibiting the same behavior as the ones loaded during DOM ready

I have implemented a jQuery plugin called timeago.js to display the time a particular article was posted, for example, showing 2 minutes ago. HTML: <p> Articles <span class='post-time' title='2014-12-03 13:42'></span> ...

Is there a way to determine whether the uploaded file has been altered?

Is there a way for me to verify if a file uploaded by the user to my server has been altered since their last upload? My database includes a log table containing User_id and FileName (each User_id is unique). Once I have read the contents of the file, I d ...

Adding markers to a Leaflet map using coordinates retrieved from a Supabase database - a step-by-step guide

I am looking to incorporate markers on a map using coordinates stored in a Supabase database column. Below is my Vue code: <l-marker v-for="(marker, index) in markers" :key="index" ref="markersRef" :lat-lng="marker.po ...

What is the best way to create a DOM element listener in AngularJS?

My goal is to monitor a <div id="please_monitor_me"> to determine if it is visible. If it is not visible, I plan to remove the margin (margin: 0;). I am aiming for no margin when the div is not visible so that it can be shown later with a burger but ...

`Switching from Fetch to Axios: A step-by-step guide`

Currently in the process of refactoring some code and need to transition from using fetch to axios. Here's the original code snippet: const createAttachment = async (formData: FormData): Promise<boolean | string> => { try { const respon ...

Utilize AJAX to extract JSON data

This is the JavaScript code I am working with: function process_file(file_name) { $.ajax({ type: "POST", url: "process_file.php?file_name="+file_name, datatype : "json", cache: true, success: function(data) { ...

Concerns about security arise when sending an access token through a POST request

I've been working on developing a straightforward CMS that utilizes AJAX requests for creating, updating, and deleting posts. Here's the process for adding a post to the blog: The user submits their email and password to the server (login.php) ...

Is there a specific identifier in the user agent string for Edge in Windows 10 S? Are there alternative methods to automatically identify Windows 10 S

How can we determine if a user is using Windows 10 S? While the usual method involves utilizing the user-agent string to identify the operating system and browser, it seems that Edge on Windows 10 S may not provide a distinct user-agent string compared to ...

How can I showcase images stored in an array using JavaScript?

I am currently developing a role-playing game (RPG). In order to enhance the gameplay experience, I am trying to implement a for loop that will dynamically generate buttons on the screen. Here is the code snippet I have created so far: $(document).ready(f ...

What is the best way to display a nested JSON object structure?

{ "Title": "Jurassic Park", "Year": "1993", "Rated": "PG-13", "Released": "11 Jun 1993", "Runtime": "127 min", "Genre": "Action, Adventure, Sci-Fi", "Director": "Steven Spielberg", "Writer": "Michael Crichton, David Koepp", "Actors": "Sam ...

What is the best way to pass the output of one grunt task to another grunt task?

I'm uncertain if grunt is capable of accomplishing this task. I have two grunt tasks that need to be executed. The first one involves creating a mock post, while the second one requires running the penthouse task to inline CSS. Any unconventional meth ...

Issues with 'md-sidenav' in AngularJs failing to respond to click event in Firefox

Currently, I am working on an Angular project that includes a sidenav based on the specifications of AngularJS Material Design. Everything seems to be functioning correctly when I click on the menu icon to control the sidenav in Chrome and other major brow ...