What sets apart window.app=new Vue({}) versus const app = new Vue({}) when included in app.js within a Vue.js environment?

What exactly is the difference between using window.app and const app in main.js within Vue?

import question from './components/Questions.vue';

Vue.http.headers.common['X-CSRF-TOKEN'] = window.Laravel.csrfToken;
window.App = new Vue({
    el: '#app',
    components: { question }
});

as opposed to

import question from './components/Questions.vue';

Vue.http.headers.common['X-CSRF-TOKEN'] = window.Laravel.csrfToken;
const app = new Vue({
    el: '#app',
    components: { question }
});

I decided to use window.app because I needed to call a method from the question component using an external jQuery function to execute the Vue method, such as App.component.method(), which worked. But is this considered a safe approach?

Answer №1

Every browser comes with the built-in window object that can be accessed from anywhere in client-side JavaScript.

https://developer.mozilla.org/en-US/docs/Web/API/Window

By using:

window.App = new Vue({
    el: '#app',
    components: { question }
});

You are assigning a variable App to the window object, allowing you to access the Vue instance using App throughout your application.

However, if you use:

const app = new Vue({
    el: '#app',
    components: { question }
});

Then you won't be able to access the app variable elsewhere in your application.

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 console.log() within a method while chaining in JavaScript/jQuery

I've been experimenting with developing jQuery plugins and I'm interested in chaining methods. The jQuery tutorial (found here: https://learn.jquery.com/plugins/basic-plugin-creation/) mentions that you can chain methods by adding return this; at ...

Encountering a problem with populating data in postgresql

After executing the npm run seed command to populate data into PostgreSQL, even though the seeding process seemed to be successful, I couldn't locate the seeded data in the PostgreSQL database. Can anyone advise on what might have gone wrong or sugges ...

Tips for utilizing the async.js library in combination with the await keyword?

Currently, I am working on integrating the async library to continuously poll an API for a transaction until it is successful. router.get('/', async function (req, res) { let apiMethod = await service.getTransactionResult(txHash).execute(); ...

Guide on how to manage the ROW_CLICK event in a module using vue-tables-2 (vuex)

In my project, there is a module called "csv" responsible for handling csv files, and I am using vue-tables-2 along with vuex: Store setup: -store -modules -csv.js -index.js index.js: Vue.use(Vuex) const store = new Vuex.Store({ modul ...

Using relative paths to showcase images in Node.js

I am currently working on my first Node.js MVC app where I am using native Node and not utilizing Express. One issue I am facing is the difficulty in displaying images from my HTML files through their relative paths. Instead of sharing my server.js and ro ...

Is there a way in JavaScript to format an array's output so that numbers are displayed with only two decimal places?

function calculateTipAmount(bill) { var tipPercent; if (bill < 50 ) { tipPercent = .20; } else if (bill >= 50 && bill < 200){ tipPercent = .15; } else { tipPercent = .10; } return tipPercent * bill; } var bills = ...

Validation within nested Joi schemas

Need help validating a nested object conditionally based on a parent value. const schema = Joi.object({ a: Joi.string(), b: Joi.object({ c: Joi.when(Joi.ref('..a'), { is: 'foo', then: Joi.number().valid(1), otherwise: Jo ...

What is causing the loss of data when attempting to access an array field within an object?

So I've been grappling with this issue. I have a collection of objects, each containing string arrays and a string based on the following interface: export interface Subscription { uid: string; books: Array<string>; } The problem arises whe ...

Save an array of messages by making separate API calls for each one

I have a function that makes an API call to retrieve a list of message IDs. Here is the code: function getMessageList(auth) { api.users.messages.list({ auth: auth, userId: 'me', }, function(err, response) { if (er ...

Comparing Data Manipulation Techniques: Server Side vs Client Side Approaches in Reddit API Integration

As I delve into creating a simple Node/Express web application that fetches data from the Reddit API, performs some alterations on it, and intends to present this information using Charts.js on the client side, I find myself facing a dilemma due to my limi ...

Embedding HTML Tags within an array element

The task at hand involves adding an HTML element from Array Value to the Document Object Model template: { 0: { h1: '<h1>Hi</h1>' }, 1: { h2: '<h2>Hi</h2>' }, 2: { h3: &a ...

No matter what I attempt, my presentation refuses to align in the center

My slideshow, which is powered by jQuery/JS and involves absolute positioning for each image, is causing me trouble when trying to horizontally center it on the page. No matter what I do, I can't seem to get it right. The challenge is not only getting ...

The scrollbar remains visible on mobile devices

I'm attempting to remove the scrollbar from all elements in my Vue + Vite application. I do not want to disable scrolling, just hide the scrollbar itself. To achieve this, I have employed the following code snippet. *::-webkit-scrollbar { display: ...

Narrow down product selection by multiple categories

I'm currently in the process of working with Express and MongoDB, where I have data items structured like the following: { "_id": { "$oid": "63107332e573393f34cb4fc6" }, "title": "Eiffel tower&quo ...

Update of component triggered only upon double click

I'm encountering an issue with my parent component passing products and their filters down to a subcomponent as state. Whenever I add a filter, I have to double click it for the parent component to rerender with the filtered products. I know this is d ...

What is the best redux middleware for my needs?

As I followed the guide, I discovered a variety of middlewares available for Redux applications. Redux Thunk, Redux Promise, Redux Promise Middleware, Redux Observable, Redux Saga, Redux Pack Selecting a middleware is based on personal preference. Howeve ...

Verify the occurrence of an element within an array inside of another array

Here is the scenario: const arr1 = [{id: 1},{id: 2}] const arr2 = [{id: 1},{id: 4},{id: 3}] I need to determine if elements in arr2 are present in arr1 or vice versa. This comparison needs to be done for each element in the array. The expected output sho ...

Create a bespoke AngularJS directive for a customized Twitter Bootstrap modal

I am attempting to create a unique custom Twitter Bootstrap modal popup by utilizing AngularJS directives. However, I'm encountering an issue in determining how to control the popup from any controller. <!-- Uniquely modified Modal content --> ...

Preventing JQuery from interrupting asynchronous initialization

I am currently developing an AngularJS service for a SignalR hub. Below is the factory code for my service: .factory('gameManager', [function () { $.connection.hub.start(); var manager = $.connection.gameManager; return ...

Getting the input tag id of an HTML form can be achieved by using the "id

<?php $i = 1; $query1 = mysql_query("SELECT * FROM `alert_history` ORDER BY `alert_history`.`id` DESC LIMIT ".$start.",".$per_page.""); while($result = mysql_fetch_array($query1)){ echo '<td colspan = "2">& ...