Adding more dynamic parameters to the external script in index.html using Vue.js

I am looking to pass username and userEmail from the getters/user method in Vuejs, which is within index.html. Here is an example of how I would like it to be passed:

<script>window.appSettings={app_id:"appId", contact_name: "Alexander the Great",
        contact_email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="442528213c042129342d36216a" target="_blank">[email protected]</a>",};</script>

What is the correct way to achieve this in Vuejs?

Answer №1

It's crucial to consider timing when working with Vue and window.appSettings. To ensure proper execution, it is recommended to write to window.appSettings within a created or mounted function.

For instance:

{
   mounted() {
      window.appSettings = window.appSettings || {};
      window.appSettings.userId = this.userId;
   }
}

Since these values will be used by an external script, Vue must set them BEFORE the script loads. One way to achieve this is by having Vue handle the loading of the external script itself. This can be done by dynamically creating a script element and adding it to the dom:

{
   mounted() {
      // write the values first
      window.appSettings = window.appSettings || {};
      window.appSettings.userId = this.userId;

      // now load any external scripts:
      var script = document.createElement('script');
      script.src = 'hellozest.io/widget/...';
      document.body.appendChild(script);
   }
}

While this approach may work, it does require Vue to have knowledge of and responsibility for external scripts. In general, it might be preferable to address this issue differently:

If userId and userEmail are accessible on the backend of your application, consider setting 'window.appSettings' on the server side to keep the Vue application simple. Alternatively, if only Vue has access to these values, you could isolate this functionality within a single Vue component to maintain code structure.

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

Using backslashes to escape JSON values within a value in Angular

When retrieving JSON data from the backend, I often encounter an issue where the value is set to "key": "\$hello" and it results in an "Unexpected token d". Is there a way in Angular to handle or escape these characters once received from the server? ...

Guide to executing a batch file using electron

I've been struggling all morning to find a solution. I've gone through several tutorials, but I still can't wrap my head around how this should work. In my Electron app, there is a button that, when clicked, should execute a batch file (hpm ...

What is the best way to customize column width in AG-Grid?

I am looking for a way to dynamically set column width in my table. I have provided a stackblitz example which demonstrates that when changing the screen size, only the table border adjusts, but not the column widths. Is there a way to also change the col ...

Passing data to server-side PHP script using AJAX technology

Currently, I'm facing an issue with passing variables to a PHP script using onclick. It seems that I am making a mistake somewhere. To demonstrate the problem, let's say I have the following code snippet in my main page: <img src="myImage.jp ...

Displaying Data in Table Using Ajax Request

I'm working on a project that involves creating an HTML table from an ajax request pulling SharePoint list items. The screenshot provided demonstrates how it functions and what it displays after the button is clicked. However, I am looking for a way t ...

How can I pass a variable name as an argument in Vue?

I am exploring ways to create a method that can efficiently load and assign JSON files to dynamic variables. Despite my efforts, varA and varB are not being populated as expected: data() { return { varA: Array, varB: Array } }, ...

The Discord Bot is displaying an error message labeled as "DiscordAPIError[50035]"

Here is the code in my ticket_system.js file: const { Client, MessageEmbed, MessageActionRow, MessageButton, Modal, TextInputComponent, } = require("discord.js"); const settings = require("./settings"); ...

Creating a Mongoose schema to store an array of objects, where updates will automatically add new objects

const mongoose = require('mongoose'); module.exports = mongoose.model('GridModel', { Request_Id : { type : Number, required : true }, viewStudents : { type : Array , default : [] } }); The mongoose model above needs to b ...

What are the steps for pairing jsplumb with vuejs?

I successfully implemented the jsPlumb script in an .html file within the script tag and it is functioning properly. <body> <div id="q-app"></div> <!-- built files will be auto injected --> <script> jsPlumb.rea ...

Increase the size of the grid system column upon clicking on a Bootstrap icon

I am using Google Maps in a tab with Bootstrap, but the map is too small. I would like to change the Bootstrap grid system when I click on a FontAwesome icon: the first column should turn into col-md-8, and the second column should become col-md-4. Here i ...

Custom input field in Material UI not communicating properly with Redux form

I am currently utilizing Material UI and React to implement a custom input field. While using redux form for form validation, I have encountered an issue where the onBlur and onFocus events are not being dispatched successfully. Interestingly, if I switch ...

Is there a way to modify the document title using .ready()?

As I work with nested layouts in Ruby on Rails, one particular layout requires me to extract a string from a div and use it as the title of the document. What is the proper method (if there is one) to accomplish this task? <script type="text/javascri ...

Exploring the different routing options for Nuxt.js: Dynamic versus Basic Routing

Can anyone suggest the best way to set up routing in Next.js for only Home, Gallery, and Contact us? Should I use dynamic routing or just keep it basic? Any ideas on how to path them? I'm still learning, so I would appreciate some guidance. I've ...

`Cannot recompile the `Product` model as it has already been compiled. Please try again

I attempted to reference my productSchema within my purchaseSchema but encountered the following error: OverwriteModelError: Cannot overwrite Product model once compiled. What steps can I take to resolve this issue? Here is my product schema: mongoose = ...

Implement a function that runs upon Page Load using Javascript

Here is some Javascript code that loads a map with different regions. When you hover or click on a country, additional information about that country is displayed on the right side of the map. I would like to have a random country already displaying infor ...

Control the outcome of ajax response

I have implemented an ajax post method to retrieve data from the backend. $.ajax({ type: "POST", url: URL_one, data: submitData }).then(function (response) { console.log("Ajax response", response); }); Upon inspecting th ...

Finding the Number of Days Between Two Dates in AngularJS Using JavaScript

When I receive two dates from a web service in the format below: var dateone = "2016-08-21T07:00:00.000Z"; var datetwo = "2016-08-28T07:00:00.000Z"; var datediff = datetwo - dateone; var numdays = Math.round(datediff); console.log("Number of Days is " + n ...

Why is my Node.js Connect middleware Limit feature not functioning as expected?

Having an issue with server: var connect = require('connect'); var http = require('http'); var app = connect() .use(connect.limit('32kb')) .use(connect.urlencoded()) .use(connect.json()) .use(function(req, res){ console. ...

A glitch occurred while attempting to load content dynamically onto an HTML page using Ajax

Attempting to dynamically load content into an HTML div is causing issues for me. Whenever I try to do so, an error pops up: Syntax error HOME. (this is the expected visible content within the div). HTML: Navigation bar: <li><a href="#" onclick= ...

Transform the C# DateTime to LocalTime on the client side using JavaScript

Utilizing the Yahoo API on my server to retrieve currency information can be done through this link: Yahoo Currency API This API provides me with both a Date and a Time, which I'd like to combine into a single DateTime object. This will allow me to e ...