What is the best way to share props with all routes in vue.js?

I need to make sure that all components have access to the BASE_URL variable. Here is an example of my App.js:

<template>
<router-view></router-view>
</template>

<script>
import addJoke from './components/addJoke.vue'
import showJokesAll from './components/showJokesAll.vue'

export default {
   components: {
    'add-joke': addJoke,
    'show-jokes-all': showJokesAll
  },

  data () {
    return {
        BASE_URL : 'http://127.0.0.1:8090'       
    }
  }
}
</script>

<style> 
</style>

And here is the code from routes.js:

import showJokesAll from './components/showJokesAll.vue';
import addJoke from './components/addJoke.vue';

export default [
  {path:'/', component: showJokesAll, props: {BASE_URL: 'http://127.0.0.1:8090'} },
  {path:'/add', component: addJoke, props: {BASE_URL: 'http://127.0.0.1:8090'}  }  
]

In the showJokesAll component, I have the following:

<script>
import axios from 'axios';

    export default {
        name: 'showJokesAll',
        props: ['BASE_URL'],
      data () {
        return {
            jokes:[]            
        }
      },
      methods: {
      },

      created() {
        axios.get( this.BASE_URL + '/api/jokes').then( response => this.jokes = response.data);

    }
}
</script>

But it seems like the components are not receiving the BASE_URL properly.

[Vue warn]: Error in created hook: "ReferenceError: BASE_URL is not defined"

Any suggestions on how I can resolve this issue?

Answer №1

To utilize the property defined with props: ['BASE_URL'], you can access it through this.BASE_URL:

axios.get( this.BASE_URL + '/api/jokes').then(/*...*/)

Answer №2

If you create a file with Mixins that contain data or a function returning your BASE_URL, you can then import the mixins file using:

import myMixins from './my_mixins.js'

Mixins offer a versatile way to share reusable functionalities for Vue components. A mixin object can include any component options. When a component utilizes a mixin, all options within the mixin will be combined into the component's own options.

If you need to handle the state of the data, consider exploring Vuex.

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

Updated:

Also take a look at Vue Instance Properties.

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

Should I generate an array or pull data directly from the database?

Hey there, I've got this JavaScript app and could really use some input or tips. Here's the idea: Users log in to try and defeat a 'boss', with each player working together in the game. Let's say the 'boss' has 10 millio ...

Is there an issue with the jQuery ajax function when it comes to sending the RegistrationId to our server?

Beginning to work with the pushNotification service for my Android app, I successfully received a registration ID from the GCM server and attempted to send this ID to our server using a jQuery AJAX function. My intention was to send this ID after the user ...

A guide on accessing the first element in an array when performing multiplication within the Interval component in React.js

I am having trouble initiating an if statement from number 0 once the window is loaded, as it seems to be skipping over 0 and starting from 1 instead. Can someone please assist me in understanding how this works? showAnime = () => { let counter ...

Tips for accessing elements within a jQuery tab

When a user clicks on a tab, I want to be able to access elements inside that tab. $('.myTabs').tabs({ activate: function(event,ui){ console.log("I need to retrieve the contents of the activated tab..."); } }); Just to note, I ...

Is it possible to maintain HTML, JS, and CSS files as separate entities when developing Vue.js components, similar to how it is

Is it possible to maintain separate HTML, JS, and CSS files while creating Vue.js components? I recently read the "Why Vue.js doesn't support templateURL" article which discusses this topic. "Proper modularization is a necessity if you want to bu ...

Error: Unable to split function. Attempting to retrieve API response via GET request using ngResource

I am trying to retrieve some data from an API using ngResource by utilizing the get method. Even though I have set up a factory for my resource, when implementing it in my controller, I encounter an error stating URL.split is not a function. I'm stru ...

The communication between Node.js Express and the front end is experiencing synchronization issues

I'm facing an issue where a property is mysteriously disappearing when I try to send an object from my nodejs server to the front end. server router.post('/cart/retrieve', (req, res) => { let cart = req.session.cart; let prodId ...

Display the data received from the client on the NodeJS server

I have a basic html file that includes the following snippet of javascript: <script type="text/javascript"> $.ajax({ url: 'http://192.168.X.X:8080', data: '{"data": "1"}', dataType: ...

Error encountered: Difficulty rendering Vue 3 components within Google Apps Script

Currently delving into Vue and Vue 3 while coding an application on Google Apps Script. Following tutorials from Vue Mastery and stumbled upon a remarkable example by @brucemcpherson of a Vue 2 app functioning on GAS, which proved to be too challenging in ...

Exploring the challenges of implementing the Lob Node API wrapper within a MeteorJs project due to conflicts with the 'fs' module

I recently updated to the latest version of Meteor (1.13) which now supports NPM. I decided to add the Lob.com NPM to my project and started working on a letter function. However, I encountered the following error: Uncaught TypeError: fs.readdirSync is ...

Include a photo in the notification when utilizing the sendToTopic function

I am looking to utilize the sendToTopic method for sending notifications to a topic. Is there a way to include an image in the notification? It seems that notification.imageUrl is not available as an option. ...

What is the best way to ensure that this JavaScript code functions properly when dealing with business operating hours

Using this javascript code allows me to check if a business is open based on its operating hours. It's effective for times like 17:00-23:00, but how can I modify it to work for hours past midnight, such as 0:30 or 1:00 in the morning? var d = new D ...

When scrolling, use the .scrollTop() function which includes a conditional statement that

As a newcomer to jQuery, I've been making progress but have hit a roadblock with this code: $(window).scroll(function(){ var $header = $('#header'); var $st = $(this).scrollTop(); console.log($st); if ($st < 250) { ...

Using Vuex: how to access the modules variable within an action

In my Vue application, I have a global store structured as follows: // Note: These Stores Are Modularised, please refer to: [https://vuex.vuejs.org/guide/modules.html] for more information. const store = new Vuex.Store({ modules: { surfers: surfers, ...

What is the most effective way to manage and respond to multiple events while also organizing the overall structure of

I am currently in the process of planning a complex web application using WebGL and Three.js. As I experiment with different tests, I have encountered a problem that is raising many questions for me. I am unsure of the correct approach to take and would gr ...

What are the steps to implement session storage within a Puppeteer automation script?

Currently, I am attempting to retrieve the encounter id from a Puppeteer script that launches a browser. These scripts are executed on AWS synthetic canaries. However, when running the script, I encounter the following error: sessionStorage is not define ...

Retrieve the data contained within a displayed embed tag that includes a src attribute

Can anyone provide guidance on how to retrieve the content of an embed tag using src attribute? I have an embed tag pointing to a custom page as src. I tried to use jquery to access the rendered content but I am not getting anything back. Any suggestions ...

Update the referenced lists in ng-admin

I'm currently working with ng-admin alongside a restful API, I have various referenced lists that undergo frequent updates from the server side. Is there a method to automatically refresh these referenced lists every 5 seconds using ng-admin? EDIT: ...

What is the best way to display recently added information?

I'm curious about why the newly added data isn't showing up in the template, even though it does appear when using console.log (check out ViewPost.vue). After adding a new post, this is the result: result.png. Does anyone know how to fix this? ...

Saving form data with a tinymce textarea, radio button, and checkbox to the database

My form contains multiple textarea fields, radio buttons, checkboxes, and a select input. Initially, I was able to submit the form using PHP without any issues. However, when I integrated TinyMCE with one of the textareas, I had to introduce JavaScript to ...