Incorporate Vue into a template using variables and props

Currently in the process of building a vue app and wondering how I can seamlessly integrate it into a template while passing variables (props) into it.

When I execute npm run dev, the app and all its components are coded with no issues.

After running npm run build, I end up with some js files in my build folder that were created by webpack.

I have come across suggestions on stackoverflow about simply loading these files into my template, creating an html element with the id "App", and letting the app initialize itself automatically.

However, I am facing a challenge now: the app makes Ajax requests which target different URLs depending on the environment (dev: api.local, test: api.testsystem.com, prod: api.livesystem.com, and so on).

This requires me to pass the URL from outside into the app. We do not build the app during deployment since it resides in a separate repository from the websites where it will be used. Plans include manually copying the build files to these projects or providing a CDN-like URL for other projects to load it. These other projects could be symfony-based websites, typo3 plugins, and more.

In React, I vaguely recall initiating an app like

React.render('app.js', {props: 'api-url': 'http://api.local'});
. How can this be achieved in vue?

Is it possible to do something like this:

new Vue(
  <template>
    <App :api-url="api-url" />
  </template>

  <script>
    import App from "path/to/app.js";

    export default {
      data() {
        api-url: "inject url here"
      }
    }
  </script>
);

Alternatively, could I add a data attribute such as

<div id="App" data-api-url="http://url">
and then try accessing it within the app?

I have also come across mentions of an env-loader, but I am uncertain if it would be beneficial in my specific scenario.

Answer №1

In discussions about various environment modes, it is important to familiarize oneself with the documentation on launching a Vue app in different environment modes.

One approach is to create separate .env files for each mode and load process.env with the corresponding file. Alternatively, you can initialize Vue.js with NODE_ENV=development as an example, and verify process.env.NODE_ENV to ensure the correct variables are passed where needed.

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

How come my ajax function is not processing when the form is submitted?

Having an issue with validating a form where I need to check if a username is available before submission. Although all functions, including the PHP script for checking the username, are working properly, I'm unable to prevent the form from submitting ...

Trying to decide between using a Javascript or HTML5 PDF Editor?

I am in need of a solution that enables users to edit PDF files directly on an ASP.NET web page. This functionality is intended for creating templates and adding blocks/form fields to existing PDFs, complete with rulers and other necessary features. Desp ...

Tips on automatically adjusting the width of a div to fit the content, maintaining center alignment, and ensuring the contents float to the left

I am facing an issue with a div element that has multiple children. My goal is to have the children neatly fit to the bottom left of the grid when the window expands, utilizing the next available space efficiently. However, as the div expands with the wind ...

Remove the "x" character from the phone field if an extension is not provided in the Jquery masked input plugin

Currently utilizing the jquery Masked input plugin. The mask I have applied to a field is as follows: "?999-999-9999 x9999" Why is there a ? at the beginning? This was implemented to prevent the field from clearing out when an incomplete number is ente ...

What is the method to obtain the zoom level in IE5 using JavaScript/jQuery?

Currently, I am using IE11 and have enabled emulation in the developer tools to change the document mode to 5. My goal now is to determine the current zoom level, which I adjust in the settings of IE. https://i.stack.imgur.com/DYftF.png The code snippet ...

How to Display Bootstrap4 Modal in VueJS without using Jquery

Is there a way to display a Bootstrap modal from a function in VueJS using vanilla JS? I am working on a project that only uses standard Bootstrap 4 and not BootstrapVue. //component.vue <template> <div> <button type="button" class ...

Package.json failing to enable NodeJS unsafe-perm functionality

Attempting to execute a npm install command with a preinstall script in my package.json. Despite being aware of it being considered an antipattern, I need to run certain scripts as root. The approach works when adding a .npmrc file with the content unsafe ...

Can a directive be designed to function as a singleton?

Our large single page app includes a directive that is utilized in various locations across the page, maintaining its consistent behavior and appearance each time. However, we are experiencing an issue with this directive due to the ng-repeat it contains, ...

Leveraging the $broadcast method within a $interval function in AngularJS

After extensively searching this site and using Google, I have been unable to find a solution. I have one module dedicated to services and another for the app itself. In the services module, I have the following code snippet: $interval(function(){ $ro ...

Generating a constantly evolving 3D model and keeping it current within a web browser

My website already has a large user base, and I am looking to create a 3D visual representation of data on one of the pages. This model needs to be easily updatable based on each user's database information (imagine a square board with a ball whose po ...

Extracting specific key-value pairs from JSON data

Working with JSON data, I encountered a need to pass only specific key-value pairs as data to a component. Initially, I resorted to using the delete method to remove unwanted key-value pairs, which did the job but left me feeling unsatisfied. What I truly ...

Can you explain the distinction between firstChild and childNodes[1]?

Exploring the distinction between child nodes and child elements within JavaScript DOM: For instance, var myTbodyElement = myTableElement.firstChild; versus var mySecondTrElement = myTbodyElement.childNodes[1]; Is it possible to interchangeably use firs ...

Ways to avoid route change triggered by an asynchronous function

Within my Next.js application, I have a function for uploading files that includes the then and catch functions. export const uploadDocument = async (url: UploadURLs, file: File) => { const formData = new FormData(); formData.append("file" ...

How to effectively pass custom props or data to the Link component in Next JS

As I dive into Next JS, I've hit my first roadblock. Currently, I am working on a page that showcases various podcast episodes with preview cards on the homepage. The card component code looks like this: import React from 'react'; import Li ...

Invoking a child component's method using a parent event

Hello, I am a newcomer to VueJS and JavaScript and would greatly appreciate your assistance. I am facing an issue with my method "greet" not working, and I am uncertain as to why. When I click on the button "change to bar," I receive the following error: ...

JavaScript error occurring when trying to validate Ajax response

I am attempting to create a report using a dynamically generated form. The form loads successfully through XMLHttpRequest, but the validation for the form fields does not seem to be working. I have experimented with using eval() and found that it only work ...

The MaterialTable is unable to display any data

After calling the fetch function in the useEffect, my getUsers function does not populate the data variable. I am unable to see rows of data in the MaterialTable as the data structure is in columns. I need help figuring out what I'm doing wrong. func ...

Calculate the number of views using Laravel and VueJS

Looking for assistance with tracking the number of visits to each article on my Laravel and Vue-based articles site. Previously used eloquent-viewable package in Laravel, but unsure how to implement in Laravel + Vue. Can anyone provide guidance on this? ...

Is there a way to access data from a different cart template containing personalized values on Shopify?

After analyzing the values required from product.json, I realized that the current method is not efficient. The client-side ends up processing unnecessary information and every new product or option adds to the request load. Below is the script responsible ...

Challenges with Property Decorators in Angular 6

Hello there, I've been testing out this sample decorator code and encountered an issue that I can't seem to figure out. The error message I received was "cannot read property 'firstname' of undefined". It appears that the 'this&apo ...