简体   繁体   中英

vue.js add event listener to button in Render function

I want using Vue.js Render function to make component in javascript.Now I can make a HTML structure one SPAN and one BUTTON.when I click the button,I expect it output in console,but it just not work.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>

or on codepen Any response is welcome and thank you .

Your use of the createElement method is incorrect when building your button, since you are passing the wrong series of arguments.

First off, you should set the inner html + via your button attributes object, not via the second argument which is reserved for the data object, per the documentation :

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

As such, you should structure your buttonsAttrs object as follows:

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

Second, you should pass the buttonAttrs as the second argument in your createElement call per the above documentation:

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

See this working codepen .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM