vue自学入门-6(vue jsx)

目录:

vue自学入门-1(Windows下搭建vue环境)

vue自学入门-2(vue创建项目)

vue自学入门-3(vue第一个例子)

vue自学入门-4(vue slot)

vue自学入门-5(vuex state)

vue自学入门-6(vue jsx)

vue自学入门-7(vue style scope)  

vue自学入门-8(vue slot-scope)

vue组件视图可以通过模板,也可以通过jsx方式

1、删除HelloWorld<template>内容

-----------------方式1---------------------

2、export default中增加render

 3、运行

4、点击事件和react的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、运行正常

-----------------方式2---------------------

 6、再换一种写法使用createElement

createElement可以简写为h,或者其它字符比如

7、增加点击事件

 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>
原文地址:https://www.cnblogs.com/zhaogaojian/p/12356139.html