vue开发过程常用的JSX语法

参考资料:https://juejin.cn/post/7114063575122984973

在Vue项目的开发过程,经常会使用到JSX语法,对常用的JSX语法分类做个笔记,方便需要之时查阅

动态绑定class


数组形式:

class={[

' pt-30 pb-20 mb-20',

this.undesirable_redeem_amt > 0 ? 'line-bottom' : '',

]}

JS模板字符串形式:

className={

`pt-30 pb-20 mb-20

${this.undesirable_redeem_amt > 0 ? 'line-bottom' : ''}

}

文本插值 单大括号{}

在单大括号内支持任何有效的JavaScript表达式


const element = <h1>Hello, { name }</h1>

条件渲染


this.isSingleProductRedeemType && tips.push(<p>若部分取出,单产品赎回份额不少于1万份</p>)

if(flag) {

return <h1>预约</h1>}

else {

return <h1>已预约<h1>

}

使用三目运算符


this.isSingleProductRedeemType && tips.push(<p>若部分取出,单产品赎回份额不少于1万份</p>)

等价于

this.isSingleProductRedeemType ? tips.push(<p>若部分取出,单产品赎回份额不少于1万份</p>) : null

列表渲染


get tipsRenders(): { render: () => VNode }[] {

const render = (jsx: VNode) => ({ render: () => jsx });

return this.tips.map(it => {

return typeof it === 'string' ? render(<span>{it}</span>) : render(it);

});

}

标签属性绑定


const href = 'https://devui.design/'

const element = <a href={href}>DevUI Design</a>

style样式绑定

样式绑定需使用双大括号{{}}


const width = '100px'

const element = <button style={{ width, fontSize: '16px' }}></button>

事件绑定

事件绑定使用大括号{},事件名前需要加上on前缀,


render(

<div class="state">

部分成交

<i

class="iconfont iconfont-info tip"

onClick={() => this.popTip(TradeSubdivisionState.partDeal)}

></i>

</div>

);

不带参数时:

onClick={this.popTip}

事件修饰符

jsx中给事件增加修饰符需要借助withModifiers方法。


import { withModifiers, defineComponent, ref } from 'vue'

render(

<div class="state">

部分成交

<i

class="iconfont iconfont-info tip"

onClick={withModifiers(() => this.popTip(TradeSubdivisionState.partDeal), ['self'])}

></i>

</div>

);

posted @ 2022-12-16 17:05  进击的totoro  阅读(176)  评论(0编辑  收藏  举报