How to use Vue.js to attach an event listener to a button using the Render function

I am trying to use the Vue.js Render function to create a component in JavaScript. Currently, I have set up an HTML structure with one SPAN and one BUTTON. When I click the button, I expect it to output in the console. However, it is not working as expected. Here is my code:

<script src="https://unpkg.com/vue/dist/vue.js"></script>
<div id="app">
  <counter></counter>
</div>
<script>
    var a = {
           data () {
              return {count: 1}
            },
            methods: {
              inc () {console.log(this.count)}
            },
            render:function(h){
              var self = this
              var buttonAttrs ={
                    on:{click:self.inc}
                  }
              var span = h('span',this.count.toString(),{},[])
              var button = h('button','+',buttonAttrs,[])
              return h('div' 
                ,{},
                [
                  span,
                  button
                ])

            }
      }

  new Vue({
    el:'#app',
    components:{
      counter : a
     }}
  )

</script>

View and interact with the code here on CodePen. Feel free to provide any feedback or suggestions. Thank you!

Answer №1

It seems like there is an issue with your use of the createElement method while creating your button. The problem lies in the arguments you are passing.

You should avoid setting the inner HTML using the second argument, as it is reserved for the data object according to the documentation:

// {Object}
// A data object corresponding to the attributes
// you would use in a template. Optional.
{
    // (see details in the next section below)
},

To rectify this, ensure that your buttonsAttrs object is structured correctly:

var buttonAttrs = {
    on: { click: self.inc },
    domProps: {
        innerHTML: '+'
    },
};

Additionally, make sure to pass the buttonAttrs as the second argument in your createElement call, as per the documentation above:

var button = h('button', buttonAttrs, []);

You can also view a working example on codepen.

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

Only a select few expandable elements in the jQuery accordion

How can I create an accordion menu with only a few expandable options? I am looking to include the following items in my menu: Home, Support, Sales, Other The "Home" option is just a link without any sub-menu. Clicking on it should direct users to a spec ...

Production CORS issue (Flask containerized with Docker, static Vue files, NGINX setup)

Everything is functioning correctly on the development environment, as expected. In my setup, I have a Flask app (API) running in a Docker container, a PostgreSQL database in another Docker container, and a Vue.js app for the front-end. For production de ...

What causes JavaScript parseFloat to add additional value in a for loop implementation?

I am facing a challenge where I need to convert an array of strings into an array of decimal numbers. The original array of strings is structured like this: var array = [" 169.70", " 161.84", " 162.16", " 176.06", " 169.72", " 170.77", " 172.74", " ...

Why do images show up on Chrome and Mozilla but not on IE?

I have tested the code below. The images display in Chrome and Mozilla, but not in IE. The image format is .jpg. Can someone please assist? bodycontent+='<tr class="span12"><td class="span12"><div class="span12"><img class="span ...

Encountering an error when trying to destructure a property of null

The concept of destructuring is fascinating, but I have been facing some challenges when trying to destructure nested objects. Consider the following code snippet: const { credit: { amount }, } = userProfile This can be risky because if the &ap ...

What is the most effective way to stop zooming when focusing on form fields on iOS or similar devices when using font sizes of 16px or lower?

It appears that many proposed solutions involve changing the text to 16px or using JavaScript to determine if the phone is an iPhone. However, altering the style may not be the most practical solution and checking for specific devices like iPhones could ...

Guide on creating CSS for webkit scrollbar through the use of Javascript

I have a div named 'dynamic' with text inside, and I am applying styling to it using javascript. var styleElement = document.createElement("style"); styleElement.appendChild(document.createTextNode("#dynamic { color: red; }")); document.getEleme ...

What is the reason behind create-next-app generating .tsx files instead of .js files?

Whenever I include with-tailwindcss at the end of the command line, it appears to cause an issue. Is there any solution for this? npx create-next-app -e with-tailwindcss project_name ...

Unique Shader - Three.js

I have been attempting to implement a custom shader in Three.js, following various examples, but I am encountering issues. Below is the code snippet I have been working with: var vertex = "void main(){vec4 mvPosition = modelViewMatrix * vec4( position, 1. ...

Data retrieved from the server is not being displayed by Ag-Grid

I am currently utilizing Ag-Grid for Angular to display datasets retrieved from my back-end server. The component responsible for visualizing the table is showcased below: dataset.component.html <div class='body-container'> <ag-gr ...

Material UI fails to display any content

I attempted to integrate a navbar into my website, but React is not displaying anything. Even creating a new project did not resolve the issue. Additionally, Stack Overflow restricts posts that contain mostly code and I am unsure why. Here is my App.js im ...

Sending CSV files to users using MEANJS

Currently, I am employing the MEANJS framework to create a Node.js application. Essentially, I have JSON data stored in MongoDB and I am utilizing the json-csv NPM module to convert it into a CSV format. I managed to successfully download the CSV file loc ...

The initial material UI button conceals itself

I have encountered an issue with Material UI buttons in my code. Here's how I am using them: <main className="content"> <div className="buttons"> <Button variant="contained&qu ...

The program successfully executes its function, however, an error message appears stating: "Error: Cannot alter headers after they have already been sent to the client."

During testing the update post feature in my MERN project, I encountered a strange issue. The post would update successfully, but the page would disappear and I would receive the following error message. However, after restarting the server, the updated po ...

Using Angular, we can assign an array iteration as the value for a dropdown option in

Following the controller logic: $scope.form_data = { day: 'Day' }; $scope.days = [ 'Day',1,2,3,4,5,6,7,8,9,10, 11,12,13,14,15,16,17,18,19,20, 21,22,23,24,25,26,27,28,29,30, 31 ]; In the html section: <select n ...

What is the best way to transfer information from an app.js file to an index.ejs file within Routes?

I'm encountering an error where the variable 'blogs' that I am passing as an object containing data to the index page is not defined. Here is the code for the index page: Any help or guidance on how to resolve this issue would be greatly ap ...

The operation to remove the child element could not be completed

var first_content = document.getElementById('first-content'), offered_games = document.getElementById('offered-games'); for(var i = 0, e = offered_games.children; i < e.length; i++) { e[i].onmouseenter = function() { var ...

"The function you are attempting to call is not defined within the HTMLButtonElement.onclick

How do I trigger the DeleteRow and EditRow functions when clicking on the Delete Button and Edit Button? <button style="margin-right: 5px;" type='button' onclick='return EditRow(@i)' id='@editrow' class='btn btn-prima ...

Designing templates for websites and applications using node.js

Simplified Question: As I delve into improving my skills with node.js, I'm exploring the concept of templating. How would using node to serve one HTML file and loading page-specific information through AJAX/sockets impact performance and design princ ...

Removing an element from an array of objects in Javascript

My situation involves an array containing objects: var items = [{ id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3"}]; In addition, I have this specific object: var itemToRemove = { id: 2, text: "test2" }; My objective is to veri ...