Invoke a Vue component's function using a property

Can a Vue component's method be triggered by passing the method's name to one of its properties?

// main.vue
<navigation :button-left="goback()"></navigation>



// navigation.component.vue
...
props: ["buttonLeft"],
...
methods: {
  goback() {
    console.log('Run this.');
  },
},
...

I attempted this approach, but encountered an error:

[Vue warn]: Property or method "goback" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option, or for class-based components, by initializing the property. See: https://v2.vuejs.org/v2/guide/reactivity.html#Declaring-Reactive-Properties.

Answer №1

Absolutely, achieving this is quite feasible.

The simplest approach would involve passing a basic string, such as

<navigation button-left="goBack" />

Keep in mind that there is no requirement for v-bind.

Subsequently, within your component, you can make use of the prop value. For instance...

export default {
  template: `<button @click="triggerButtonLeft">Click</button>`,
  props: ['buttonLeft'],
  methods: {
    triggerButtonLeft () {
      if (typeof this[this.buttonLeft] === 'function') {
        this[this.buttonLeft]()
      } else {
        console.error('Invalid method name:', this.buttonLeft)
      }
    },
    goBack () {
      console.log('Executing this.')
    }
  }
}

You haven't specified the event to activate the method execution, so I've chosen a click event.

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

Nashorn poses a security threat due to its ClassFilter vulnerability

Encountering some troubles with Nashorn and came across a concerning security vulnerability highlighted here: It appears that someone can easily execute code using this command: this.engine.factory.scriptEngine.eval('java.lang.Runtime.getRuntime().ex ...

Working with MySQL in Node.js using async/await

Struggling with utilizing async/await in Node.js with MySQL as it consistently returns an undefined value. Can someone shed light on what could be causing this issue? See my code snippet below. const mysql = require('promise-mysql'); var co ...

When transmitting a variable from JavaScript to PHP using Ajax, the data appears to be missing

While attempting to pass a simple string variable using an onclick event, I encountered an issue where the request was successful but the response in the console displayed as empty. Additionally, the xvar variable did not come through properly resulting in ...

What is the best way to retrieve an ng-model parameter within a controller?

I'm working on implementing a PUT method in my controller and need to bind the new value back to it. I've tried: <div ng-app="myApp" ng-controller="personCtrl"> <form> First Name: <input type="text" ng-mod ...

Interactive VR Experience Using A-Frame and Three.JS Raycasting

I am currently working with two different objects in my A-Frame scene, a cylinder and a polygon, both representing Three.js 3D Objects. I would like to make it so that the polygon changes when hovered over, similar to how the cylinder does. If you'd ...

React: How to retrieve values from a dynamic dropdown menu

For my React project, I have integrated ant design components. Currently, I am working on adding dynamic select functionality and retrieving the selected values. I have successfully implemented dynamic dropdown selection. However, I am facing an issue wi ...

What is the best way to reset everything back to its original position by clicking anywhere on the screen except for the specified div?

Is there a way to make the entire screen reset to its original state with just one click anywhere on the screen, rather than having to click a specific button? Any assistance on this matter would be greatly appreciated. Thank you! JQUERY CODE $(".readNow ...

What sets apart toBeInTheDocument from getBy* in @testing-library/react?

Can you distinguish between these two methods in react-testing-library? expect(screen.queryByText('<something>')).toBeInTheDocument(); And screen.getByText('<something>'); (The specific getBy* and queryBy* operation are no ...

Modifying Data in Another Component in VueJS

I have a classic Vue Component structured like the following: Vue.component('bar', { template: `<div class="bar"></div>`, data () { return { blocks: [ ] ...

Adding a new key-value pair to a JSON data structure

Here is the JSON object that I am currently handling: { "name": "John Smith", "age": 32, "employed": true, "address": { "street": "701 First Ave.", "city": "Sunnyvale, CA 95125", "country": "United States" }, ...

Assessing the string to define the structure of the object

Currently, I am attempting to convert a list of strings into a literal object in Javascript. I initially tried using eval, but unfortunately it did not work for me - or perhaps I implemented it incorrectly. Here is my example list: var listOfTempData = [ ...

What is the best way to overlay a 2D text layer on top of a Three.js scene?

I have successfully created a basic 3D scene using JavaScript. The scene features a THREE.SphereGeometry paired with a THREE.MeshNormalMaterial. However, I am now faced with the challenge of adding a text layer on top of the Three.js scene. Query: What is ...

Having trouble with parsing JSON data using jQuery?

I am currently working on retrieving a result set using postcodes with jQuery autocomplete. However, the code I have implemented seems to be displaying an empty set of rows. <html lang="en"> <head> <meta charset="utf-8> <title>Ausp ...

JavaScript string constant remains unterminated

When I pass a value from the database to this function, I encounter a JavaScript issue. Here is the code snippet: showrootcausedetails('showrootcause',true,'<%# eval("Root Cause Analysis").ToString() %>') I understand that I nee ...

Hold off on running the code until the image from the AJAX request is fully loaded and

Currently, I am facing a challenge with my code that aims to determine the width and height of a div only after it has been loaded with an image from an AJAX request. The dimensions of the div remain 0x0 until the image is successfully placed inside it, c ...

Running a JavaScript file from a C# application

I am currently using a .js file to create an array of strings, and I find that Javascript is the most suitable language for this task. However, I am now looking to access this array in my C# application. Since Javascript is unable to access the filesystem ...

Encountering an error while attempting to utilize the split function in browser.umd.js due to

Hey there, I seem to be encountering an issue that states: Cannot read properties of undefined (reading 'split'). I came across this error message in the console https://i.sstatic.net/3nICv.png Upon clicking the link to the error, it directs me ...

Configuring date and time picker options on the fly

I am attempting to dynamically set the options for this datetimepicker plugin. This is what I have in my controller $(document).ready(function () { var today = moment(new Date()).format("YYYY-MM-DD"); var tomorrow = moment().add(1, 'days& ...

Retrieving data from a script within a React component

How can I access a variable from a script inside a React component? I am performing device detection on Node and sending the resulting object to the client (React) within index.ejs. <script type="text/javascript">window.deviceType = <%- deviceT ...

Kohana ajax causing removal of JQuery Data attributes

Currently, I am developing an application where jquery data is used to pass variables to HTML elements. It has been successful in one part of the site when the data attributes are added to a tr tag. The following code works: <tr class="js-instructions ...