[前端] 在vue中写jsx的几种方式

1941 0
Honkers 2022-10-21 15:42:49 | 显示全部楼层 |阅读模式
目录

    版本render函数jsx/tsx使用jsx的几种方式
      使用js对象注册component使用.vue文件vue2.7在.vue文件中结合compositionApi和jsx



版本

本文版本配置 vue: 2.7.2 vue-cli: ~4.5.18; 本文代码github仓库地址

render函数

render函数和vue中的template是互斥的,template最终是要编译成virtual Dom的,而render函数可以更直接构建virtual Dom; virtual Dom由树状的vnode构成,h函数可以构建vnode
vue templates are compiled into virtual DOM render functions. vue also provides APIs that allow us to skip the template compilation step and directly author render functions
If both render and template are present in a component, render will take higher priority.
如果render和template同时出现,render会有更高的权限(vue2不太一样,下面会说)。
这些在文档中有更直接的说明vue3 render函数

jsx/tsx

jsx类似于h函数,都是更直接使用javascript来构建DOM,需要注意的是jsx语法需要去编译处理,有的脚手架可能有预先配置,有的没有。
在typescript下需要编写tsx

使用jsx的几种方式


使用js对象注册component

When not using a build step, a Vue component can be >defined as a plain JavaScript object containing >Vue-specific options:
vue组件也可以直接使用普通的js对象来注册
  1. // 定义一个js文件,导出组件对象
  2. // componentObject.js
  3. export default {
  4.   data() {
  5.       return {
  6.           msg: 'hello'
  7.       }
  8.   },
  9.   created() {
  10.       setTimeout(() => {
  11.           this.msg = 'hello world'
  12.       }, 1000);
  13.   },
  14.   render() {
  15.       return <h1>{this.msg}</h1>
  16.   }
  17. }
复制代码
  1. <script>
  2. import componentObject from './../components/componentObject.js'
  3. export default {
  4.   components: {
  5.     jsxComponent
  6.   }
  7. };
  8. </script>
复制代码
使用.vue文件

这里如果template和render函数如果同时指定的话,会用template覆盖掉render,显然是template优先级更高,跟文档上的render优先级更高不一样
  1. // sfcJsx.vue
  2. <!-- <template>
  3.   <div>test</div>
  4. </template> -->
  5. <script>
  6.   export default {
  7.     data() {
  8.       return {
  9.         msg: 'i am sfc jsx'
  10.       }
  11.     },
  12.     created() {
  13.         setTimeout(() => {
  14.             this.msg = 'i am sfc jsxxxx'
  15.         }, 1000);
  16.     },
  17.     render() {
  18.         return <h1>{this.msg}</h1>
  19.     }
  20.   }
  21. </script>
复制代码
vue2.7在.vue文件中结合compositionApi和jsx

目前在setup中return jsx会报错,目测是loader没有支持(有知道解决办法的老师傅也可以告诉我一下..),只能在setup使用compositionApi再加上render函数里写jsx
  1. // sfcJsx.vue
  2. <script>
  3. import { ref } from 'vue';
  4. export default {
  5.   setup() {
  6.     const count = ref(0);
  7.     setTimeout(() => {
  8.       count.value = 12
  9.     }, 1000);
  10.     return {
  11.       count
  12.     }
  13.   },
  14.   render(h) {
  15.     return (
  16.       <h1>{this.count ? <span>11</span>: <span>22</span>}</h1>
  17.     )
  18.   }
  19. }
  20. </script>
复制代码
到此这篇关于在vue中写jsx的几种方式的文章就介绍到这了,更多相关vue使用jsx 内容请搜索中国红客联盟以前的文章或继续浏览下面的相关文章希望大家以后多多支持中国红客联盟!
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Honkers

荣誉红客

关注
  • 4009
    主题
  • 36
    粉丝
  • 0
    关注
这家伙很懒,什么都没留下!

中国红客联盟公众号

联系站长QQ:5520533

admin@chnhonker.com
Copyright © 2001-2025 Discuz Team. Powered by Discuz! X3.5 ( 粤ICP备13060014号 )|天天打卡 本站已运行