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

Javascript encountering issues with recognizing 'self.function' within an onclick event

Recently, I have been working on enhancing a Javascript file that is part of a Twitter plugin. One of the key additions I made was implementing a filter function for this plugin. Here is a snippet of the script showcasing the relevant parts: ;(function ( ...

Modify the styling of the initial picture in a Google Drive file

Having an issue.. I am working on a website where each page is managed through Google Drive. I need to change the CSS styling of only the first image on one specific page. Using :first-child won't work because the HTML structure contains "p > span ...

Changing the value of props from a child component

As a newcomer to Vue, I am embarking on the journey of creating a "dropdown" component. My objective is to utilize it from a parent component in the following manner: <my-dropdown v-model="selection"></my-dropdown> The variable selection is m ...

Tips for resolving the error "React import attempt":

I'm a beginner in learning React and I encountered this error when trying to export NavigationMenu and import it into Navigation: Failed to compile ./src/components/Navigation.js Attempted import error: 'NavigationMenu' is not exported from ...

The issue of elements flickering while being hidden and shown with jQuery has been observed in both Chrome and

Having trouble with a simple animation using jQuery? While it may work smoothly in Firefox, you might be experiencing flickering in Chrome and Edge. Check out this jsfiddle for reference: HTML <div id="boxes-wrapper"> <div class="box"></ ...

The React apexchart heatmap's height remains static despite attempting to change it through state updates

Seeking to dynamically resize the height of an "Apexcharts heatmap" based on server data. Despite attempting to manipulate code in various lifecycle methods, including componentDidMount() and where the data is received, I have not been successful. Within ...

Advanced filtering of arrays in JavaScript

The data structure I am working with consists of nested arrays of objects, each containing further nested arrays ad infinitum. Imagine deep nesting levels. Let me illustrate my goal with an example. I have a collection of groups. Each group contains heroe ...

Guide to recursively iterating through an array of objects in TypeScript/Javascript

In my current programming challenge, I am dealing with an array of objects that have two properties: target and source. Additionally, there is a designated starting source to begin with. The goal is to start from the starting source and recursively find a ...

Dealing with errors when working with cross-domain JSONP requests in jQuery can be a

My attempts to capture a bad request error using my jquery code have been unsuccessful. $.get('http://example.com/', {}, function () {}, 'jsonp') .done(function () { // never fires }) .fail(function () { // never fires }) .a ...

What is the process for setting up a banner on one page that will automatically be reflected on all other pages?

Is there a way to have a banner in a div and display it on the home page so that it automatically appears on all other pages without needing to place the code on each page individually? Any assistance would be greatly appreciated :) ...

ReactJS state refuses to update

In my FreeCodeCamp leaderboard table, I have implemented functionality where clicking on the highlighted table header calls different URLs based on sorting criteria. The application either calls https://fcctop100.herokuapp.com/api/fccusers/top/recent or ht ...

Preventing Past Dates from Being Selected in JQuery Date Picker

Need help with a date picker that only allows selection of the 1st and 15th dates of each month. How can I prevent users from selecting previous dates? <link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" ty ...

Opting for a .catch over a try/catch block

Instead of using a traditional try/catch to manage errors when initiating requests like the example below: let body; try { const response = await sendRequest( "POST", "/api/AccountApi/RefundGetStatus", JSON.stringify(refundPara ...

creating a JSON object in PHP that can be easily parsed by JavaScript

In my project, I have an extensive list of items, each item further divided into four sub-items. While it's convenient for me to organize this data in nested arrays using PHP, I encounter issues when trying to transfer them as a JSON object to the cli ...

Sort table rows by checkbox value in javascript

Is there a way to use javascript or JQuery to group the rows in this table by Office or Age based on the checkbox option selected? For example, if the Office checkbox is checked, the table rows should be grouped by Office. If the Age checkbox is checked, ...

Are Lazily Instantiated Singletons a Thing in AngularJS?

After browsing through the AngularJS documentation, I came across an interesting detail about AngularJS services: AngularJS lazily instantiates services, meaning they are only created when a component in the application requires it. Services in AngularJ ...

What is the best way to use jQuery to toggle the visibility of a <panel>?

My objective is to display a panel with two labels on a button click, but I'm facing issues achieving this functionality. When I click on the button (id=Button1), the panel (id=anspanel) should appear, but it remains hidden even after clicking the but ...

Showing the unique identifier instead of the actual data in HTML for a Firebase Object using Angularfire

Currently, I am utilizing AngularFire for a specific project. The structure of my firebase Object is as follows: { mainKey: { key1:value1, key2:value2 }, mainkey2: { key3:value3 } } The data has been inputted in a manner tha ...

Encountering a 404 error in Angular MVC project while trying to load a

Trying to access an edit partial named AddEditPersonModal.cshtml from a different folder in my MVC project, in order to load its contents into a UI Bootstrap modal using Angular. However, when the index.cshtml page loads, I encounter a 404 error related to ...

Problems during the installation of Webpack

Encountering Error Setting up Webpack and Babel with NPM npm ERR! Unexpected end of JSON input while parsing near '...pdragon":"^0.7.0","to' npm ERR! A complete log of this run can be found in: npm ERR! A complete log of this run can be found ...