How can I efficiently update Vue data externally?

const app = createApp({
  data() {
    return {
      unique_id: 0
    }
  }
})

I implemented an autocomplete feature on a specific input field. My goal is to send the chosen id to a Vue application when a label is selected.

onSelectItem: ({label, value}) => {
    app.unique_id = value;
}

This functionality was working perfectly in an earlier version of Vue.js. However, I am now facing issues where external JavaScript functions cannot access the Vue app's methods. What would be your recommendation for resolving this challenge?

Answer №1

There may be occasions where you need to access and update the instance's data.

In Vue JS 2, this task was simpler, but Vue JS 3 has increased its encapsulation. However, it is still possible to modify state from external sources. You can find more information about this here

If you are using Vue with build steps, which is common, your setup will look something like this:

const app = createApp({
    data() {
        return {}
    },
})
    .mount('#app');

If you try typing app in the browser console, it will return null because of the scope limitation imposed by compiled .js files.

However, if you attach app to a global object like document:

document.app = createApp({
    data() {
        return {}
    },
})
    .mount('#app');

Now when you type app in the console, it will no longer be null, but the actual Vue instance. This allows you to access and manipulate the instance's data through the app.$data property.

But what if the instance includes components and you want to modify their $data? In previous versions, you could access children using the $children property. Now, you need to assign a ref to each component and then access them by their ref name. For example:

app.$refs.alertComponent.$data.message = "New message!"

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 to display and download a PDF file on a JSP web page

Can anyone help me with a simple trick to solve this question I have? In my project folder, I have 5 PDF files named file1.pdf, file2.pdf, file3.pdf, file4.pdf, and file5.pdf. I want to display these files in 5 rows on my webpage, each row containing VIEW ...

What could be causing my React child component to not update when changes are made to an array passed down in props after fetching new data?

My Profile.js component is responsible for fetching activity data related to a specific user from the URL parameter and updating the profileActivity state. This state is then passed down to my child component, ProfileActivity.js, where it should be display ...

Issues with premature execution of Angular JS code have been observed at times

Currently facing an issue with my code where the updateProduct() function call is happening before the forEach loop begins running on about 1 out of every 10 page loads. Not sure why this is occurring or how to solve it. Any insights on what might be causi ...

Exploring Angular 8 Route Paths

Working on an Angular 8 project, I encountered an issue with my code: src/app/helpers/auth.guard.ts import { AuthenticationService } from '@app/services'; The AuthenticationService ts file is located at: src/app/services/authentication.servic ...

Remove any javascript code from the ajax modal when it is closed or hidden

I am in the process of creating a music website that showcases songs along with their lyrics. One of the features I have added is a lyrics button that, when clicked while a song is playing, opens up a modal displaying the live lyrics. Everything works per ...

Getting rid of the scrollbar in Internet Explorer

Instead of just removing the scrollbar, I want to ensure that scrolling capabilities remain intact. This is important because I want to create a 'slide show' effect on the website where users can click 'next' and scroll through content ...

What is the reason that selection disappears when right-clicking on highlighted text to bring up the context menu?

Currently, I am utilizing Material UI's context menu implementation in my project. On Chrome browser, everything is functioning flawlessly, as depicted below. Chrome: https://i.stack.imgur.com/i7eA1.gif However, I have encountered a peculiar issue ...

Retrieve the attributes of a class beyond the mqtt callback limitation

Currently, I am utilizing npm-mqtt to retrieve information from a different mqtt broker. My objective is to add the obtained data to the array property of a specific class/component every time a message is received. However, I'm facing an issue wher ...

Ajax Form Submission

My query relates to a combobox I have integrated: <select id='addOPTION' onchange='fillADDid(this.value);'> <option value=0>Select</option> <option value=1>etc</option> <option value=2>etc</option ...

transition from mapStateToProps to using hooks

Just dipping my toes into the world of React (hooks) and learning by writing code. I'm grappling with converting MapStateToProps to hooks, specifically stuck on one part just before 'currentItem'. Here's the original code snippet: co ...

What could be preventing the fill color of my SVG from changing when I hover over it?

I am currently utilizing VueJS to design an interactive map showcasing Japan. The SVG I am using is sourced from Wikipedia. My template structure is illustrated below (The crucial classes here are the prefecture and region classes): <div> <svg ...

I have been dynamically inserting div elements into the DOM using JavaScript, using the appendChild method to add them and later removing them with removeChild. Strangely, when trying to append a div

There seems to be an issue in the code snippet below. The function create() works fine the first time, but encounters a problem on the second run at the line boxWrapper.appendChild(box);. It appears that the removeChild method is causing some disruption in ...

The functionality of Dnd-kit nested is functioning properly, however, one specific component is unfortunately

Currently, I am dealing with a two-dimensional array that results in two nested dnd-kit drag and drop fields. The nested dnd functions correctly; however, the first one sorts items when moved without any animations (even when moving my div). Below is the ...

Use Material UI Grid to create a horizontal line design instead of focusing on making the

Is there a way to turn off responsiveness for the material UI grid similar to how it can be done with a basic HTML table? While an HTML table scales down and adds a horizontal scroll bar, the material UI grid remains responsive as shown in the example belo ...

Error message: Unable to run npm script serve due to permission issues with vue-cli-service

Attempting to execute a basic vue project, but encountering difficulties running it on my openSUSE TW (20200615) system. I have NVM for managing my node installation. Here is my current environment: nvm --version # 0.35.3 node --version # v14.4.0 npm --v ...

What are your thoughts on combining a JSON object with HTML?

When using ASP.NET MVC, it is possible to return a JSONResult. return JSON(new { View = RenderViewAsString("MyView", model), wasSuccessful = true}) This approach combines HTML and data in a single JSON object. The goal is to utilize strongly typed HtmlHe ...

Concentrate on what comes next

Within my JavaScript code, I have the following line: $('input')[$('input').index(this)+9].focus(); I intended for this line to focus on the next element. However, when it executes, I encounter the following error: Error: [$rootSc ...

Ways to implement a resize function in Angular JS without relying on the document and window objects

Is there a way to convert the following jQuery code into Angular JS without relying on Document and Window? Can we write the code without utilizing Document.ready and window? ...

Utilizing libraries in JavaScript

For a while now, I've been grappling with an issue related to importing modules into my main JavaScript script. I recently installed the lodash library via npm and I'm trying to import it into my main script so that I can utilize its functionali ...

Obtain identical socket event in two separate useEffect hooks

I am facing an issue where I want to access the same event in two different useEffect functions on the same page. Despite my attempts, it doesn't seem to work as expected. Below is what I have tried so far. I'm wondering if it's possible to ...