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

Utilizing the <webview> functions within Electron: A comprehensive guide

After checking out the documentation for the Electron <webview>, I attempted to use some of the listed methods with no success. In inspecting the properties of the <webview> element, I found that its prototype is labeled as webview (__proto__ : ...

Transmitting an Array Using an Ajax Call

Is there anyone knowledgeable in Ajax here? I'm struggling with sending a javascript array in an ajax request. Can someone provide me with an example of how the ajax request should be formatted? My goal is to gather all the javascript data, package it ...

Is there a way to save a Morris.js chart as a PDF file

I have successfully created a Morris.js Bar Chart using data from PHP and MySQL. Now, I am looking for a way to export this chart into a PDF format. I have attempted to do so using the FPDF library but I am struggling with the implementation. Can anyone ...

Utilize jQuery to automatically assign numbers to <h1-h6> headings

Looking to develop a JavaScript function that can automatically number headings (h1- h6) for multiple projects without relying on CSS. Currently achieving this with CSS: body { counter-reset: h1; } h1 { counter-reset: h2; } h2 { counter-reset: h3; } ... T ...

Sending information to a component through navigationPassing data to a component

When attempting to move from one component to another page using routes and needing to send parameters along with it, I have experimented with passing them as state through history.push(..) like the following code. However, it does not seem to be working a ...

What could be preventing req.session from being set in node.js?

Having trouble setting anything for req.session My goal is to securely store oauth token and secret in a session for verification after the authorize callback. Below is the code snippet: var express = require('express'), app = express ...

Creating toggling elements in Vue.js using dynamic v-show based on index and leveraging falsey v-if

What is the most effective way to use v-show for toggling elements based on their index? I have been able to toggle the elements, but when you click on the element that is already open, it does not close. <div v-for="(btn, index) in dataArray"> ...

What is the best way to show the initial image within every div that has the class name .className?

I am looking to only show the first image in each div with the class name "className." This... <div class="className"> <p>Yo yo yo</p> <p><img src="snoop.jpg" /></p> </div> <div class="className"> Hel ...

Jquery vertical menu with a dynamic sliding animation from the right side to the left side

Hello everyone, I am looking to have my vertical menu slide from right to left instead of the typical top to bottom sliding that comes with using .toggle() in jQuery. Specifically, when the hamburger menu is clicked, I want the menu to slide out from right ...

How to retrieve a value from PHP using Ajax?

I am struggling to implement ajax for adding a div to display an error message. Despite my efforts, I keep receiving null as the error message instead of the expected value. The occurrence of null is traced back to <?php echo json_encode($_SESSION[&ap ...

Creating a Vue template using Javascript is a straightforward process

My app has a specific scenario where I need to define a template using JavaScript. For instance, after importing my template import MyTemplate from "./MyTemplate"; export default { components: {MyTemplate}, } Is it possible to declare the tem ...

The property 'clone' is undefined and cannot be read

Currently, I am using Fullcalendar to update events. My goal is to execute an ajax callback to retrieve the edited version of a specific event. The endpoint for this request should be at /controls/:id/edit. To achieve this functionality, I have implemented ...

Why does the node.js app only run from the command prompt and not directly?

I have a basic vbscript that launches two nodejs apps necessary for my server's operations. Dim objShell Set objShell = Wscript.CreateObject("WScript.Shell") objShell.Run "node C:\!webroot\site.name\server\pubsub.js" objShell.Run ...

When comparing strings, if they match, replace them with bold text

Today, I faced a challenging brain teaser that kept me occupied for over an hour. The task at hand is to compare two strings: the text input from the field and data-row-internalnumber. The goal is to determine if they match and then bold only the last let ...

Refreshing the page causes the Angular/Ionic Singleton instance to be destroyed

I have a TypeScript singleton class that is responsible for storing the login credentials of a user. When I set these credentials on the login page and navigate to the next page using Angular Router.navigate (without passing any parameters), everything wor ...

Guide to displaying or concealing the header using PHP

Once the add button is clicked, the text should be hidden and the form should be displayed. Check out my code below: <h2 style="font-size: 2em; margin-bottom: 0.75em; margin-left: -1%;">Specify Co-Owners for self occupied property</h2> <div ...

Generating additional react-select dropdowns depending on the selection made in the initial dropdown menu

I am currently working on a travel website. I am in need of a dropdown menu for users to select the number of children they will be traveling with, with options for 1, 2, or 3. If the user chooses 1 child, then an additional react-select element should ...

Overwriting Resolved Data in Angular UI-Router Child States

I'm facing an issue where the resolve function is the same in both parent and child states, but I need it to return different values based on the child state. Instead of customizing the implementation for each state, it seems to be inheriting the beha ...

Having trouble adding a JavaScript library to my Nuxt project

I've encountered an unusual issue. I am attempting to incorporate a hover-effect library (https://github.com/robin-dela/hover-effect) into my Nuxt project. Here is the code I have in my contact.vue file within the script tags: import hoverEffect fro ...

The Owl-Carousel's MouseWheel functionality elegantly navigates in a singular, seamless direction

Issue at Hand: Greetings, I am facing a challenge in constructing a carousel using Owl-Carousel 2.3.4. My goal is to enable the ability to scroll through my images using the mousewheel option. Code Implementation: Incorporating HTML code : <div style ...