详解利用jsx写vue组件的方法示例


Posted in Javascript onJuly 17, 2017

前言

本文主要给大家介绍的是关于利用jsx写vue组件,下面话不多说,来一起看看详细的介绍吧。

我们平常写vue的组件时,一般都是用的是模版,这种方式看起来比较简洁,而且vue作者也推荐使用这个方式,但是这种方式也有一些它的弊端,例如模版调试麻烦,或者在一些场景下模版描述可能没那么简单和方便。

下面我们要讲的是如何在vue里面写jsx,知道react的人应该都知道jsx,jsx的一个特性就是非常灵活,虽然有的人觉得jsx很丑陋,把逻辑都写到模版的感觉,但萝卜青菜各有所爱,适合自己适合团队的就是最好的。

在使用jsx之前我们需要安装一个babel插件(babel-plugin-transform-vue-jsx )

安装方式:

npm install\
 babel-plugin-syntax-jsx\
 babel-plugin-transform-vue-jsx\
 babel-helper-vue-jsx-merge-props\
 babel-preset-es2015\
 --save-dev

然后再.babelrc里面添加:

{
 "presets": ["es2015"],
 "plugins": ["transform-vue-jsx"]
}

接着我们就可以愉快地在vue里面编写jsx了。

Test.vue

<script>
export default {
 props: ['onClick', 'isShow'],
 
 data() {
  return {
   test: 123
  };
 },
 
 render() {
  return (
   <div class="test" onClick={ this.onClick }>
    { this.test }
    { this.isShow + '' }
   </div>
  );
 }
}
</script>

可以看到我们把jsx写在了render方法里面,render方法是vue2.0才支持的,用来提供对虚拟DOM的支持,也就是说只有vue2.0才支持jsx语法转换。

这里要注意的一点是vue里面编写jsx和在react里面的jsx语法还是有一点不一样的。

以下是一段覆盖大部分语法的vue jsx代码:

render (h) {
 return (
 <div
  // normal attributes or component props.
  id="foo"
  // DOM properties are prefixed with `domProps`
  domPropsInnerHTML="bar"
  // event listeners are prefixed with `on` or `nativeOn`
  onClick={this.clickHandler}
  nativeOnClick={this.nativeClickHandler}
  // other special top-level properties
  class={{ foo: true, bar: false }}
  style={{ color: 'red', fontSize: '14px' }}
  key="key"
  ref="ref"
  // assign the `ref` is used on elements/components with v-for
  refInFor
  slot="slot">
 </div>
 )
}

可以看到DOM属性要加domProps前缀,但这里lass和style却不需要,因为这两个是特殊的模块,而且react的class用的是className,vue却用的class。事件监听是以“on”或者“nativeOn”为开始。

实际上vue2.0的模版最后都会被编译为render方法,所以模版声明的组件和jsx声明的组件最后都是一样的。

上面的jsx最后会被编译成下面这样:

render (h) {
 return h('div', {
 // Component props
 props: {
  msg: 'hi'
 },
 // normal HTML attributes
 attrs: {
  id: 'foo'
 },
 // DOM props
 domProps: {
  innerHTML: 'bar'
 },
 // Event handlers are nested under "on", though
 // modifiers such as in v-on:keyup.enter are not
 // supported. You'll have to manually check the
 // keyCode in the handler instead.
 on: {
  click: this.clickHandler
 },
 // For components only. Allows you to listen to
 // native events, rather than events emitted from
 // the component using vm.$emit.
 nativeOn: {
  click: this.nativeClickHandler
 },
 // class is a special module, same API as `v-bind:class`
 class: {
  foo: true,
  bar: false
 },
 // style is also same as `v-bind:style`
 style: {
  color: 'red',
  fontSize: '14px'
 },
 // other special top-level properties
 key: 'key',
 ref: 'ref',
 // assign the `ref` is used on elements/components with v-for
 refInFor: true,
 slot: 'slot'
 })
}

这也意味着两种形式的组件是可以相互引用的。

有时候我们难免会在模版里引入jsx编写的vue组件或者在jsx编写的vue组件里引入模版组件,这里还是有些需要注意的事项:

1.在模版里面引入jsx的组件,可以通过components引用,另外props的编写从驼峰式改为连接符:

<template>
 <div class="wrapper">
 <Test :on-click="clickHandler" :is-show="show"></Test>
 </div>
</template>
 
<script>
import Test from './Test.vue';
 
export default {
 name: 'hello',
 components: {
 Test
 },
 data() {
 return {
  msg: 'Welcome to Your Vue.js App',
  show: true
 };
 },
 methods: {
 clickHandler(){
  this.show = !this.show;
 }
 }
};
</script>

2.在jsx里面引入vue模版组件,这里没有什么要注意的,除了连接符式的属性要转换成驼峰式,还有一个需要注意的是指令,如果用了jsx,那么内置的指令都不会生效(除了v-show),好在内置指令大部分都可以用jsx描述。那么自定义指令要怎么用呢?

自定义指令可以使用“v-name={value} ”语法,如果要支持指令参数和modifier可以用“v-name={{ value, modifier: true }} ”语法:

<script>
import Vue from 'vue';
 
Vue.directive('my-bold', {
 inserted: function (el) {
 el.style.fontWeight = 900;
 }
})
 
export default {
 props: ['onClick', 'isShow'],
 
 data() {
  return {
   test: 123
  };
 },
 
 methods: {
  afterLeave() {
   console.log('afterLeave')
  }
 },
 
 render() {
  const directives = [
   { name: 'my-bold', value: 666, modifiers: { abc: true } }
  ];
 
  return (
   <transition onAfterLeave={this.afterLeave} name="fade">
    <div class="test" onClick={this.onClick} v-show={ this.isShow } v-my-bold>
     {this.test}
     {this.isShow + ''}
    </div>
   </transition>
  );
 }
}
</script>
<style>
.fade-enter-active, .fade-leave-active {
 transition: opacity .5s
}
.fade-enter, .fade-leave-to {
 opacity: 0
}
</style>

我们还可以用原生vnode的数据格式使用自定义指令:

const directives = [
 { name: 'my-dir', value: 123, modifiers: { abc: true } }
]
 
return <div {...{ directives }}/>

扩展

如果有人觉得在vue组件里面要写data,props,computed和methods不够优雅,可以参考下这个插件vue-class-component,它能让你使用ES6的class和ES7的装饰器编写vue组件。

相关链接:

babel-plugin-transform-vue-jsx

总结

以上就是这篇文章的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对三水点靠木的支持。

Javascript 相关文章推荐
jquery 模拟雅虎首页的点击对话框效果
Apr 11 Javascript
JavaScript中把数字转换为字符串的程序代码
Jun 19 Javascript
javascript中hasOwnProperty() 方法使用指南
Mar 09 Javascript
Javascript中神奇的this
Jan 20 Javascript
jQuery中通过ajax的get()函数读取页面的方法
Feb 29 Javascript
jQuery设置聚焦并使光标位置在文字最后的实现方法
Aug 02 Javascript
js显示动态时间的方法详解
Aug 20 Javascript
使用vue-resource进行数据交互的实例
Sep 02 Javascript
微信小程序实现之手势锁功能实例代码
Jul 19 Javascript
详解项目升级到vue-cli3的正确姿势
Jan 28 Javascript
jQuery实现高级检索功能
May 28 jQuery
微信小程序3种位置API的使用方法详解
Aug 05 Javascript
Javascript实现找不同色块的游戏
Jul 17 #Javascript
Vue.js 单页面多路由区域操作的实例详解
Jul 17 #Javascript
Vue项目webpack打包部署到服务器的实例详解
Jul 17 #Javascript
JS中Safari浏览器中的Date
Jul 17 #Javascript
Vue.extend构造器的详解
Jul 17 #Javascript
原生js实现密码输入框值的显示隐藏
Jul 17 #Javascript
extjs简介_动力节点Java学院整理
Jul 17 #Javascript
You might like
php mssql 时间格式问题
2009/01/13 PHP
PHP下使用CURL方式POST数据至API接口的代码
2013/02/14 PHP
PHP利用APC模块实现大文件上传进度条的方法
2015/10/29 PHP
PHP字符串逆序排列实现方法小结【strrev函数,二分法,循环法,递归法】
2017/01/13 PHP
用javascript实现的仿Flash广告图片轮换效果
2007/04/24 Javascript
JavaScript 新手24条实用建议[TUTS+]
2009/06/21 Javascript
js日期、星座的级联显示代码
2014/01/23 Javascript
让table变成exls的示例代码
2014/03/24 Javascript
H5实现中奖记录逐行滚动切换效果
2017/03/13 Javascript
微信小程序实战之轮播图(3)
2017/04/17 Javascript
Vue中使用vux的配置详解
2017/05/05 Javascript
angular内置provider之$compileProvider详解
2017/09/27 Javascript
chosen实现省市区三级联动
2018/08/16 Javascript
详解angular2如何手动点击特定元素上的点击事件
2018/10/16 Javascript
JavaScript变量基本使用方法实例分析
2019/11/15 Javascript
js实现整体缩放页面适配移动端
2020/03/31 Javascript
JS定时器如何实现提交成功提示功能
2020/06/12 Javascript
vue-calendar-component 封装多日期选择组件的实例代码
2020/12/04 Vue.js
python之wxPython菜单使用详解
2014/09/28 Python
Python原始字符串(raw strings)用法实例
2014/10/13 Python
python使用xlrd实现检索excel中某列含有指定字符串记录的方法
2015/05/09 Python
django使用xlwt导出excel文件实例代码
2018/02/06 Python
Selenium chrome配置代理Python版的方法
2018/11/29 Python
pandas dataframe添加表格框线输出的方法
2019/02/08 Python
python3.4 将16进制转成字符串的实例
2019/06/12 Python
Python带参数的装饰器运行原理解析
2020/06/09 Python
canvas实现烟花的示例代码
2020/01/16 HTML / CSS
Delphi CS笔试题
2014/01/04 面试题
在DELPHI中调用存储过程和使用内嵌SQL哪种方式更好
2016/11/22 面试题
法院实习人员自我鉴定
2013/09/26 职场文书
护理个人求职信范文
2014/01/08 职场文书
4s店销售经理岗位职责
2014/07/19 职场文书
中班下学期个人工作总结
2015/02/12 职场文书
学前教育见习总结
2015/06/23 职场文书
Python机器学习之基于Pytorch实现猫狗分类
2021/06/08 Python
Nginx使用ngx_http_upstream_module实现负载均衡功能示例
2022/08/05 Servers