vue Self Starter -6 (vue jsx)

vue component view from a template, or by way jsx

1, delete HelloWorld <template> Content

1 --------------------- ----------------- way

2, export default increased render

 

 3, run

 

 

4. Click on the event and react like the wording of jsx

export default {
  name: 'HelloWorld',
  methods: { add () {
    // this.$store.state.count += 1
    this.$store.commit('add1')
  }},
  render () {
    return (
      <div class="hello">
        <div onClick={() => this.add()}>点我增加1</div>
      </div>
    )
  },
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}

5, operating normally

 

2 --------------------- ----------------- way

 6, and back way to write using the createElement

 

createElement can be abbreviated is h, or other characters such as

 

 

7, increasing the click event

 render (h) {
    return h('div', {
      on: {click: () => {
        console.log('click')
        this.add()
      }}
    }, '点我增加1')
  },

 8、进一步改写代码

render: h => h(App) 含义

render: function (createElement) {
    return createElement(App);
}
render (createElement) {
    return createElement(App);
}
render (h){
    return h(App);
}

按上面的写法,将render改写为

 render: h => h('div', {
    on: {click: () => {
      console.log(this)
      this.add()
    }}
  }, '点我增加1'),

发现并不能正确add,提示

 

 

打印this,下面这个this为

 

 

正确的写法this为

 

 为什么出现这种问题没有想明白,有熟悉的朋友请解答一下,正常,异常代码分别如下

render (h) {
    return h('div', {
      on: {click: () => {
        console.log(this)
        this.add()
      }}
    }, '点我增加1')
  }

render: h
=> h('div', { on: {click: () => { console.log(this) this.add() }} }, '点我增加1')

 如果想处理这个问题可以这样写,增加_this

<script>
var _this = {}
export default {
  name: 'HelloWorld',
  methods: { add () {
    // this.$store.state.count += 1
    this.$store.commit('add1')
  }},
  beforeCreate () {
    _this = this
  },
  render: h => h('div', {
    on: {click: () => {
      console.log(_this)
      _this.add()
    }}
  }, '点我增加1'),
  data () {
    return {
      msg: 'Welcome to Your Vue.js App'
    }
  }
}
</script>

 

Guess you like

Origin www.cnblogs.com/zhaogaojian/p/12356139.html