Creating a dynamic button with Vue

I need help with rendering a button on a Vue instance. I want to be able to click on the button and have another button render with a click event. When I simply mount the button, the function doesn't work.

const Hello = {
  props: ['text'],
  template: '<button v-on:click="tes"> </button> ',
};

new Vue({
  el: '#app',
  data: {
    message: 'Click me'
  },
  methods:{
        alertar: function(event){
                      const HelloCtor = Vue.extend(Hello);
            var instance = new HelloCtor({
                    propsData: {
                  text: 'HI :)'
                }
            })

                instance.$mount() // pass nothing
           this.appendChild(instance.$el)
      },
      tes: function(){
            alert('Teste');
      }
  }
})

Error:

vue.js:597 [Vue warn]: Invalid handler for event "click": got undefined

(found in <Root>)
warn @ vue.js:597
(index):52 Uncaught TypeError: this.appendChild is not a function
    at Vue.alertar ((index):52)
    at invoker (vue.js:2029)
    at HTMLParagraphElement.fn._withTask.fn._withTas

Answer №1

The issue arises when you create a child component within your parent Vue that includes the template with the binding to the tes function. As a result, the child component will search for tes within its own methods, even though it is actually a property of the parent component. This leads to the child component being unable to locate the function within its own scope. To resolve this, you need to add the function to the child component itself:

const Hello = {
  props: ['text'],
  template: '<button v-on:click="tes"> </button> ',
  methods: {
    tes: function(){
      alert('Teste');
    }
  }
};

Answer №2

Expanding on the answer provided by @Philip, it is important to note that parent methods cannot be accessed in programmatically created components. The methods must be specified within the child components themselves.

const Hello = {
  props: ['text'],
  template: '<button v-on:click="this.tes"> Vue Generated</button> ',
        methods: {
    tes: function(){
      alert('Teste');
    }}
};

new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue.js!'
  },
  mounted(){
    this.alertar()
  },
  methods:{
        alertar: function(event){
          const HelloCtor = Vue.extend(Hello);
            var instance = new HelloCtor({
              propsData: {
                  text: 'HI :)'

                }
            })

            instance.$mount() // pass nothing
          this.$refs.container.appendChild(instance.$el)
      },
      tes: function(){
            alert('Teste');
      }
  }  
})

Take a look at this fiddle for reference: https://jsfiddle.net/50wL7mdz/370645/

While there are some cases where you may be able to access parent component methods using the $parent directive, it is unlikely to work when components are created programmatically.

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

Find the total duration of all items within an array by utilizing the Moment.js library

Within an array of objects, each object contains a field named "duration" that represents a string. Here is an example of one such object: { id: 14070 project: {id: 87, name: "Test project for time tracking"} issue: {id: 10940} user: {id ...

apply styling to the placeholder with CSS

I have been attempting to customize the styling of the placeholder text. After setting the color to red within the input class, I did not see any changes. Even after conducting research and referring to this link Styling the placeholder in a TextField, I w ...

Swapping out data points using JQuery

What could be causing line 10 to return null? Click here for the code file The code seems to function properly with line 40, but not with line 10. ...

Setting up Authorization for FETCH requests in NEXT.js using .env.local

`export default function reservations() { let [reservationStock, setReservationStock] = useState([]); useEffect(() => { fetch(url, { headers: new Headers({ Authorization: "MyBasic Credentials", " ...

"Using the selected option from a dropdown list to pass to a PHP file for autocomplete functionality

Although there is no error in the code, I am facing an issue where, after selecting an option from the brands dropdown, when I type in the product field, it passes "%" instead of the brand id (1, 2, or 3). Is there a way to modify the code so that it passe ...

Encountering an error message of "Cannot POST" while trying to send data through a REST client application

Upon my attempt to add a new entry into the Doctors database I created, I encountered an error that has left me perplexed. This is how my server.js file appears: const express = require('express'); const bodyParser = require('body-parser&a ...

Implementing a function trigger upon selection in JavaScript

I'm currently studying JavaScript and working on a basic project that involves generating random strings of different lengths. If you're interested, feel free to check out my codepen code [here][1]. My question revolves around the functionality ...

Extracting specific attributes from an array to showcase on a single div

example: { "data": [ { "name": "banana", "color": "yellow" }, { "name": "kiwi", "color": "brown" }, { "name": "blueberry", "color": "blue" } ] } Instead of div, I want to use a span for each ...

Tips for defining a dynamic class variable in React with Flow

I am working with a map that assigns a reference to items, specifically in this scenario it is a video. const ref = this[`video-${index}-ref`]; I am seeking guidance on how to properly type this using Flow. The number of indexes may vary. ...

The initial loading of jQuery DataTables shows duplicate entries

Expanding on my query from the previous day: jQuery AJAX call function on timeout Following the guidance provided in the response from yesterday's post, the table successfully reloads without requiring a full page refresh every 30 seconds. However, ...

How come the item I just inserted into a JavaScript array is showing up as undefined when I try to retrieve it immediately after adding it?

Apologies for the messy code, but I'm facing an issue with my JavaScript. I can't figure out why the specified child is not considered as a task to derive from: var childrenToOperateOn = []; for (var i = 0; i < $scope.der ...

Increased wait time during initial execution

Currently facing an issue with delaying the first run of a function. I've developed a basic slideshow that is causing problems due to this delay in the initial run. My goal is to have the first run wait for 10 seconds and then maintain a 4-second del ...

Error encountered during Atom execution - The command '/usr/bin/env: 'node' was not found in the directory

Just starting out with coding on Atom and I'm stuck dealing with the same error message every time I try to run my Javascript code. bash: line 1: node: command not found /usr/bin/env: ‘node’: No such file or directory I've searched for solu ...

Having difficulty with my async custom react hooks. Is there a way to wait for the result of one hook before using it in another hook?

Having some difficulty working with custom react hooks. I've created 2 custom hooks - one for fetching an ID and another for fetching a profile using the previously fetched ID. Since the second hook is dependent on the ID, I need to await the promise ...

Guide to adding a line break following each set of 200 characters utilizing jQuery

I have a text input field where I need to enter some data. My requirement is to automatically add a line break after every 200 characters using JavaScript or jQuery. For example: aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa ...

Tips for recalling the display and concealment of a div element using cookies

My HTML code looks like this: <div id='mainleft-content'>content is visible</div> <div id="expand-hidden">Button Expand +</div> To show/hide the divs, I am using JQuery as shown below: $(document).ready(function () { ...

Employ a for loop to generate custom shapes within the canvas

EDIT: I will be sharing all of my code including the HTML and JS. Pardon me for the abundance of comments. I am attempting to generate rectangles in a canvas using a for loop (taking user input) and then access them in another function to perform certain ...

Vite/React/Express is restricting access to fetch due to the CORS policy

Currently, I'm utilizing Vite alongside React/Express for my application. The app initiated with npm run dev and is accessible at http://localhost:5173, while the backend operates on http://localhost:5000 during this phase. However, every time I attem ...

The AngularJS factory does not hold on to its value

I have developed a basic factory to store a value from my authService: app.factory("subfactory", function() { var subValue = {}; return { set: set, get: get }; functi ...

Should you include the dollar sign in a Vue HTML variable or not?

I’m a bit confused about whether or not I should include $ when using a Vue HTML variable: new Vue({ data: { a: "myData" } }); Do I need to use: <h1>My value is {{ a }}</h1> or <h1>My value is {{ $a }}</h1> What ...