Unable to access Vue component method beyond its scope

Having an issue with my Vue component that I'm trying to call a method from outside its wrapper element #app. Is there a way to register the component so I can easily call it like Component.function();

var viewController = new Vue({
  el: "#app",
  data: {},
  methods: {
    action: function() {
      alert("function called successfully");
    }
  }
});

HTML:

<div id="app">

</div>

<a @click="viewController.action()">Click me!</a>

Fiddle: https://jsfiddle.net/queeeeenz/Lja7pake/198/

Answer №1

After some experimentation, I discovered the following:

  1. It appears that using @ in elements outside of a Vue element may not work as expected.
  2. The declaration var viewModel does not seem to be connected to the window object.

Despite these challenges, I was able to successfully run the code.

JavaScript

window.viewModel = new Vue({
  el: "#app",
  data: {},
  methods: {
    test: function() {
      alert("test fuction called");
    }
  }
});

HTML

<div id="app">

</div>

<a onClick="viewModel.test()">Click me!</a>

Answer №2

Initially, it appears that you are applying a click handler in the "Vue" manner, even though it is not actually within a Vue component. This approach will not be effective.

To properly achieve your desired outcome, you must expose your function to a different scope by assigning it to a window attribute.

var viewModel = new Vue({
  el: "#app",
  data: {},
  created () {
    // The function is now accessible
    window.test = this.test;
  },
  methods: {
    test: function() {
      alert("test function called");
    }
  }
});

// Later on
window.test();

A more optimal solution would be to utilize a global event bus. Instead of exposing arbitrary functions globally, you can create a bus for communication. This allows for emitting events within the Vue application using this.$bus.$emit('...') and listening to them throughout the application. By employing a defined interface between the internal and external parts of the Vue application, unnecessary exposure of functions in the global scope is avoided, enabling better control over interactions with the application from outside sources.

import Vue from 'vue';
export const bus = new Vue();

// In another file
import { bus } from './bus';
Vue.prototype.$bus = bus;

// External code usage
import { bus } from '../../my-vue-application/bus';
bus.$emit('test');

// Within a component
var viewModel = new Vue({
  el: "#app",
  data: {},
  created () {
    this.$bus.$on('test', this.test);
  },
  beforeDestroy () {
    this.$bus.$off('test', this.test);
  },
  methods: {
    test: function() {
      alert("test function called");
    }
  }
});

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

What is the proper way to access object properties in EJS?

My server has an express API to retrieve food items and I want to display their names on my ejs index file. In order to fetch the data, I have the following code in my server.js file: app.get('/', async (req, res) => { try { fetch ...

Is PHP loaded prior to the `html body`?

I'm facing a unique challenge where I am currently transferring variables from a PHP page to hidden HTML inputs. The values are extracted from these hidden inputs using a JavaScript function that is called in the following manner: <body onload=" ...

Exploring the getJSON function within jQuery

{ "Emily":{ "Math":"87", "Science":"91", "Email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d6f7e767c51767b727e737f764f747879">[email protected]</a>", "City":"Chicago" }, "Sa ...

When attempting to upload a file in Vue Apollo, a Node crash occurs with the error message "Maximum call stack size

I've been working on setting up the front end for graphQl file upload with Apollo-boost-upload. The backend code I'm using is based on this helpful tutorial: https://dev.to/dnature/handling-file-uploads-with-apollo-server-2-0-14n7. After adding t ...

Encountering a Module not found error with a ValidationError when trying to import an SVG file within a React

I've set up a manual Webpack 5 configuration for my React project with TypeScript. I am facing an issue while trying to import an SVG icon and using Material UI in the project. The error message I'm encountering is: Module not found: ValidationEr ...

Encountered a connection error while attempting to establish a connection in Node.js

Every time I try to execute the code, I encounter this error message: throw new Error('Most middleware (like ' + name + ') is no longer bundled with express and must be installed separately ^ Error: Most middleware(like BodyParser) is ...

The scrolling event on the div is not triggering

I'm struggling with this piece of code: const listElm = document.querySelector('#infinite-list'); listElm.addEventListener('scroll', e => { if(listElm.scrollTop + listElm.clientHeight >= listElm.scrollHeight) { th ...

Concealing empty rows within a vertical v-data-table using Vue

Below is the code that can be run to showcase my issue. Design: <div id="app"> <v-app id="inspire"> <v-data-table :headers="headers" :items="desserts" hide-default-header ...

Using jQuery's ajax function to send data with a variable name of data field

I am trying to figure out how to dynamically add a variable to the name of the data field I want to send information to through ajax. Below is an example of the code I'm working on: var qty = $('#qty_'+value).val(); $.ajax({ url: &apo ...

Stop horizontal overflow of content

This unique Vuetify demo on CodePen showcases a two-column layout. The first column contains a <v-list> enclosed in a green <v-alert>. By clicking the "toggle text" button, you can switch the title of the first list item between short and long ...

Is there a way to display customized values on a particular column in a Vuetify table?

In the column named conditions, I am looking to display the count of rules > details. Please Note: The array rules has a property details.length = 2 This is what I have attempted https://i.stack.imgur.com/2LoFb.png Here is the code snippet: header ...

Using Express to request data from Mongo database and only receiving the path

I've been troubleshooting a websocket function that interacts with MongoDB to fetch some data stored in the system using 'get'. const User = require('mongoose'); const express = require('express'); const cal = require(&a ...

Adding non-reactive elements to reactive ones in VueORCombining static and dynamic components in

I am currently working on a project where I have a parent component called <v-window> that contains children elements of type <v-window-item>. The first child item is responsible for looping through data fetched from a Vuex getter and dynamical ...

JavaScript Date displaying the string in the format YYYY/MM/DD HH:MM

I'm struggling to figure out how to format a date and time string like this: "YYYY-MM-DD-HH-MM" Can anyone help me with this? Here is the code I currently have: var x = new Date(); var formattedTimeStamp = x.toString(); Current Output: Tue Oct 3 ...

Only function components can utilize hooks within their body. The useState functionality is currently not functioning as expected

Currently working on a GatsbyJS project and attempting to utilize a Hook, however encountering an error message. Initially, I decided to remove the node_modules folder and package.json.lock file, then executed npm install again, unfortunately without reso ...

Utilize the ng-controller directive with unique aliases across various sections of HTML code

I'm facing an issue with my ng-controllers when multiple controllers are used on the same page. For instance, I have one controller in the page header, another in a different section of the same page, and one in the content of the page. However, all o ...

Is there a different alternative to @JavascriptInterface in Android WebView?

I understand how to invoke a Java method within JavaScript code using the @JavascriptInterface annotation. However, I am facing an issue when trying to determine which JS method should be called from Android. Currently, I am triggering an Android Dialog ...

Utilizing AJAX to send an array of data in JSON format

I have successfully extracted specific elements from a form, stored them in an array and now want to convert this array into a JSON object to send it to a PHP file via AJAX. However, I am facing some issues with my code. Here's what I have done so far ...

Join the geomarkers in two datasets using connecting lines

I am currently developing a leaflet.js map incorporating two distinct sets of JSON data layers stored as js-files. The first dataset comprises the geographical locations of various newsrooms along with their respective IDs, while the second dataset contai ...

How can you efficiently update another ng-model value based on a select input in AngularJS using ng-change?

<select data-ng-init="selectedItem='previewWidth = 1920; previewHeight = 1080'" data-ng-model="selectedItem" data-ng-change="GetNewData(); {{selectedItem}}"> <option value="previewWidth = 1920; previe ...