国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

vue組件jsx語法的具體使用

2024-05-06 15:33:58
字體:
供稿:網(wǎng)友

如果使用render函數(shù)來寫比較復雜的vue組件,對于可讀性和可維護性都很不友好,而使用jsx就會讓我們回到更接近于模板的語法。babel轉(zhuǎn)譯器會將jsx轉(zhuǎn)譯為render函數(shù)渲染。

配置

需要用到babel插件

安裝

npm install/ babel-plugin-syntax-jsx/ babel-plugin-transform-vue-jsx/ babel-helper-vue-jsx-merge-props/ babel-preset-env/ --save-dev

.babelrc配置

在plugins中添加transform-vue-jsx

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

基礎示例

轉(zhuǎn)義前

<div id="foo">{this.text}</div>

轉(zhuǎn)譯后

h('div', { attrs: {  id: 'foo' }}, [this.text])

Note:h函數(shù)為vue實例的$createElement方法,必須存在于jsx的作用域中,在渲染函數(shù)中必須以第一個參數(shù)傳入,如:

render (h) { // <-- h 函數(shù)必須在作用域內(nèi) return <div id="foo">bar</div>}

自動注入h函數(shù)

從3.4.0開始,在用ES2015語法聲明的方法和getter訪問器中(使用function關鍵字或箭頭函數(shù)除外),babel會自動注入hconst h = this.$createElement)函數(shù),所以可以省略(h)參數(shù)。

Vue.component('jsx-example', { render () { // h 會自動注入  return <div id="foo">bar</div> }, myMethod: function () { // h 不會注入  return <div id="foo">bar</div> }, someOtherMethod: () => { // h 不會注入  return <div id="foo">bar</div> }})@Componentclass App extends Vue { get computed () { // h 會自動注入  return <div id="foo">bar</div> }}

 Vue JSX 和 React JSX對比

首先, Vue2.0 的vnode 格式與react不同,createElement函數(shù)的第二個參數(shù)是一個數(shù)據(jù)對象,接受一個嵌套的對象,每一個嵌套對象都會有對應的模塊處理。

Vue2.0 render語法

render (h) { return h('div', {  // 組件props  props: {   msg: 'hi'  },  // 原生HTML屬性  attrs: {   id: 'foo'  },  // DOM props  domProps: {   innerHTML: 'bar'  },  // 事件是嵌套在`on`下面的,所以將不支持修飾符,如:`v-on:keyup.enter`,只能在代碼中手動判斷keyCode  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' })}            
發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表

圖片精選

主站蜘蛛池模板: 梁山县| 蕉岭县| 惠州市| 永新县| 萝北县| 阳城县| 佛坪县| 会昌县| 柳河县| 莲花县| 鹤岗市| 哈密市| 城市| 广元市| 阿图什市| 宁乡县| 上杭县| 休宁县| 华池县| 顺义区| 小金县| 桦川县| 东明县| 隆子县| 运城市| 东阳市| 通渭县| 楚雄市| 资阳市| 绵竹市| 湘潭市| 永年县| 玉田县| 丽水市| 稻城县| 阿克陶县| 任丘市| 天门市| 横峰县| 湖北省| 淮阳县|