Vue: How to access Vue instance from a function outside of its scope

In my data object, there is a small section dedicated to creating a navigation menu. This menu contains buttons that should trigger specific functions. I decided to store these functions within the data object for clarity.

However, the issue arises when this does not return a Vue object. Despite attempting to incorporate the vm into the global scope, I am struggling to find an alternative solution.

Any thoughts or suggestions on how to approach this?

const data = {
  login: {
    title: "Log in",
    icon: "fa fa-sign-in",
    action: function () {
      console.log("Log in");
      // Here is where I aim to access the vm, possibly like this:
      // this.$root.showLoginBox();
    }
  }
}

Answer №1

In my opinion, it may not be the best practice to define functions outside of a Vue instance's scope that will be used by that instance.

However, if you absolutely must keep your data object where it is, you have the option to bind this to the function from within the Vue instance:

const data = {
  login: {
    action: function () {
      console.log(this)
    }
  }
}

new Vue({
  created() {
    data.login.action.bind(this)();
  }
})

You can view a working codepen example here.

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

Wait for Vue to assign data before running a function

I am facing an issue with a method in my Vue instance that performs the following actions: submitForm(confirmation) { //set price confirmation this.price_confirmation = confirmation //proceed var form = this ...

Is it possible to delay the data until the JavaScript variable has been declared and finished?

I am currently working on the following code. My goal is to ensure that the values are fully processed before executing the dispatch function. However, the issue I am facing is that the dispatch is happening before all the values are retrieved from the for ...

Troubleshooting a TypeScript Problem with React Context

In my AppContext.tsx file, I have defined the following import React, { useState, createContext } from "react"; import { Iitem } from "../utils/interfaces"; interface AppContext { showModal: boolean; setShowModal: React.Dispatch< ...

Is it possible to synchronously read a custom field from package.json?

Is there a way for users of my module to customize its functionality by defining a custom field in package.json? I'm struggling with reading it synchronously. If I need to read someField from the package.json file of an app or module that utilizes my ...

What is the best way to target and manipulate the transform property of multiple div elements in JavaScript?

Looking at this code snippet, my goal is to have all the boxes rotate 180deg with a single click, without needing to apply different ID names: function rotateAllBoxes() { var boxes = document.getElementsByClassName("box"); for (var i = 0; i < box ...

Creating a custom name for a specific node_module

Previously, we had a folder containing various typescript modules. However, we have now transformed that folder into a package. An issue arises with the existing code, as it uses webpack aliases for that particular folder. I am attempting to have those al ...

Transferring information between components and pages within Next.js involves the passing of data

I currently have an index page set up like this: getServerSideProps(){ //Making two API calls here api1() api2() return{ props:{data:gotDataApi1, data2:gotDataApi2} } } The data retrieved from these APIs is then passed to a component within the index pag ...

Using CSS or Javascript, you can eliminate the (textnode) from Github Gist lists

My goal is to extract the username and / values from a series of gists on Github Gists. The challenge lies in the fact that there are no identifiable classes or IDs for the / value. https://i.stack.imgur.com/9d0kl.png Below is the HTML snippet with a lin ...

Using Paper Checkbox to Toggle the Visibility of a Div in Polymer

Having experience with Meteor, I typically used JQuery to toggle the display of a div along with paper-checkbox: HTML: <paper-checkbox name="remoteLocation" id="remote-chk" checked>Remote Location</paper-checkbox> <div id="autoUpdate" clas ...

When attempting to retrieve data saved to req.session with express-session from a different endpoint, the data appears to be

While working on my project with express-session, I encountered a peculiar issue. I am saving the currently logged in user to the session, but when I try to access the currentUser key on the get route, I find that the value is an empty object. Strangely, i ...

Steps for incorporating a smooth transition effect into a modal popup as its height dynamically increases

I need assistance with adding a transition effect to a modal popup that automatically increases in height when content is loaded. I have tried various styles, but none of them seem to be working. .tagModal{ overflow:hidden; transition:transform ...

Tips for sending properties to a Material-UI styled component

I am facing a challenge with passing props to a component that already has internal props for handling styling. I am not sure how to manage both sets of props effectively. Below is my current setup. const styles = theme => ({ // Theme building }); ...

Loading screen featuring an outlined blueprint of design elements

Can anyone identify the technology or language used to create the preloader screen on websites like the one shown in this link? The elements have a sweeping shine effect while loading. This style of preloader screen can be seen on popular websites such as ...

Ways to enhance focus on childNodes using Javascript

I am currently working on implementing a navigation system using a UL HTML Element. Here's the code I have so far: let htmlUL = <HTMLElement>document.getElementById('autocomplete_ul_' + this.name); if (arg.keyCode == 40) { // down a ...

Is it possible to update a nested array using the onChange function in useState?

In my application, I am dealing with a simple state that consists of an array of objects. One of these objects contains another array of objects inside it. While I have successfully implemented an onChange handler to modify the basic state, I am encounteri ...

Is it possible to directly alter state in React when utilizing MobX?

The main reason I am hesitant to do this is to ensure that React updates the view appropriately. You can read more about using state correctly here. However, it appears that MobX-react handles this process for me automatically. All I have to do is decl ...

In TypeScript, the Select element does not contain an options property

Having trouble iterating through a TypeScript array. Here are the methods I'm using: getNotification(evt: string, rowIndex: number) { console.log("Production order: law has changed to " + evt + " " + rowIndex); var select = document.getEleme ...

Steps for modifying the values of a "Key-Value" pair within a nested array in MongoDB without inserting a new item

Here is the data I have:- **{ "_id" : ObjectId("5bf8048768d1e82d8bb4a477"), "customer_code" : "c100003", "vm_info" : [ { "instanceId" : "i-0495d75742b839858", "tags" : [ { "Key" : "SIDs", ...

Error: The value of data.isbn is not defined

After encountering the error message below: TypeError: data.isbn is undefined I modified the code to include the data.isbn == null condition as shown below: $.ajax({ type: "POST", url: "getInventory.php", datatype: "json", data: ({skuSta ...

Utilizing Kendo for Dynamic HTML Element Connection

Currently, I am facing a situation where I have three HTML elements. The first is a textbox labeled shipToAddress, the second is another textbox called deliverToAddress, and finally, there is a checkbox named sameAsShipToAddress. In the background, there ...