vue中使用jsx

vue中使用jsx

为什么需要使用jsx呢?这个需要搞清楚

其实vue官方也说了,对于那些非常多v-if v-else的情况,就可以尝试使用render函数或者jsx,不过render函数写简单的结构还行,结构复杂了就很蛋疼了,而既然用到render了,肯定是有一些复杂的逻辑判断,结构肯定简单不了,所以用jsx就是一个比较好的选择了
今天自己尝试了一下,也是借鉴了网上的一些例子,不过在使用图片的时候发现事情好像有点难搞
<script>
  import img_more from '../assets/images/pk/icon-more.png';
  export default {
    name: 'More',
    props: {
      type: {
        required: true
      }
    },
    data() {
      return {
        text: 'xxxxxxxjsx',
        role: 1
      }
    },
    render() {
      return (
       <div
          class={{
            btn: true,
            'btn-success': this.type === 'success',
            'btn-danger': this.type === 'danger',
            'btn-warning': this.type === 'warning'
          }}
          >
          {this.text}
          /*这种写法是可以的,图片路径通过变量传递进来,此时可以显示图片*/
          <img class={{more: true}} onClick={this.handleClick} src={img_more} alt="" />
           /* 这种写法,直接写图片相对路径,无法显示图片  是不是很蛋疼,(暂时还不知道针对图片的具体规则)*/
          <img src="../assets/images/pk/icon-more.png" alt="" />
        </div>
      );
    },
    methods: {
      handleClick() {
        console.log('点击了', this.role);
      }
    }
  }
</script>

<style scoped lang="scss">
  .more{
    width: 36px;
    height: 36px;  //设置背景图片也是可以正常显示图片的
    /*background: url("../assets/images/pk/icon-more.png") no-repeat;*/
    /*-webkit-background-size: 100%;*/
    /*background-size: 100%;*/
  }

  .btn{
    width: 100px;
    height: 50px;
    &.btn-success{
      background-color: yellowgreen;
    }
  }

</style>

从上面的代码中可以学习的有

  1. class的写法,包含已知的class以及根据变量来动态添加的
  2. 事件的添加

这个组件自己还只是开了个头,里面的逻辑还没有尝试,待我写完了在来把本文写完

猜你喜欢

转载自www.cnblogs.com/ysla/p/11902130.html