草庐IT

vue3 + tsx 的几种写法(完整版)

硅谷干货 2023-09-28 原文

环境介绍:Nodejs:14.18.0、Vite:2.7.10、Vue:3.2.26、依赖安装采用pnpm。

第一部分:环境搭建
一、使用 pnpm创建一个vite程序

 $ pnpm create vite

二、安装vite插件:@vitejs/plugin-vue-jsx

$ pnpm i @vitejs/plugin-vue-jsx

三、在vite.config.js加入jsx配置

// vite.config.js
import { defineConfig } from 'vite'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vue from '@vitejs/plugin-vue'
// https://vitejs.dev/config/
export default defineConfig({
  plugins: [vue(), vueJsx()],
})

至此,我们新建的这个vite项目已经全面支持jsx语法了。

第二部分、改造App.vue为App.jsx
jsx语法的组件命名需采用大驼峰式命名规则。

jsx文件内容的写法跟使用模板语法时,script标签内容中的写法一模一样,可以直接导出一个对象,也可以从vue中导入一个defineComponent函数,然后默认导出defineComponent函数,并传入一个对象。

注:在模板语法中setup函数选项需return出一个对象,而在jsx语法中setup需return出一个箭头函数,所有原先在template标签中书写的内容需写在该函数体内,并且函数体只能有一个根标签。

// App.js
import { defineComponent } from "vue";
import HelloWorld from "./components/HelloWorld.vue";
import Logo from "./assets/logo.png";
export default defineComponent({
   name: "App",
   components: { HelloWorld },
   setup() {
     return () => (
       <>
         <img alt="Vue logo" src="/{Logo}" />
         <HelloWorld msg="Hello Vue 3 + Vite" />
       </>
     );
   },
});

第三部分:组件定义:
一、定义函数式组件

const App = () => <div>Vue 3.0</div>;

二、在函数式组件使用render函数

const App = {
   render() {
     return <div>Vue 3.0</div>;
   },
 };

三、推荐写法(除了指令、样式其余跟模板语法无异)

import { defineComponent } from "vue"
export default defineComponent({
     setup() {
         return () => {

             <div className="nameInfo">欢迎</div>

         }
     }
})

第四部分、语法介绍
一、样式相关语法介绍
1、如直接导入css文件,则该文件中的class类名可在项目的任何组件中使用,相当于全局类名(属性名class需要写成className)。

// App.css
.nameInfo{
     color:red;
}
// App.jsx
import { defineComponent } from "vue"
import "./App.css"
export default defineComponent({
     setup() {
         return () => {
             <div className="nameInfo">欢迎~</div>
         }
     }
})

2、vite天然支持CSS modules,任何以 .module.css 为后缀名的 CSS 文件都被认为是一个 CSS modules文件。导入这样的文件会返回一个相应的模块对象:

/* example.module.css */
.red {
   color: red;
}
import { defineComponent } from "vue"
import style from "./example.module.css"
export default defineComponent({
     setup() {
         return () => {
             <div className={style.red}>欢迎~</div>
         }
     }
})

3、内联样式写法。

import { defineComponent } from "vue"
export default defineComponent({
     setup() {
         return () => {
             <div style={{ color: "red" }}>欢迎~</div>
         }
     }
})

二、vue常用指令语法
1、v-text

 import { defineComponent, ref } from "vue";
 export default defineComponent({
   name: "HelloWorld",
   setup() {
     const text = ref("欢迎");
     return () => (
       <>
         <h1 v-text={text.value}></h1>
       </>
     );
   },
 });

2、v-html

import { defineComponent, ref } from "vue";
export default defineComponent({
   name: "HelloWorld",
   setup() {
     const text = ref("欢迎");
     return () => (
       <>
         <h1 v-html={text.value}></h1>
       </>
     );
   },
});

3、v-show

import { defineComponent, ref } from "vue";
export default defineComponent({
   name: "HelloWorld",
   setup() {
     const visible = ref(true);
     setTimeout(() => {
       visible.value = false;
     }, 2000);
     return () => (
       <>
         <div v-show={visible.value} style={{ color: "red" }}>
           欢迎
         </div>
       </>
     );
   },
 });

4、v-if、v-else-if、v-else无法直接使用,需使用逻辑与、逻辑或、三元表达式实现条件渲染。

import { defineComponent, ref } from "vue";
export default defineComponent({
   name: "HelloWorld",
   setup() {
     const h1Show = ref(true);
     const h2Hide = ref(false);
     const h3Show = ref(true);
     return () => (
       <>
         {h1Show.value && <h1>这个显示</h1>}
         {h2Hide.value && <h2>这个不显示</h2>}
         {h3Show.value ? <h3>h3Show.value为true显示</h3> : <h3>h3Show.value为false显示</h3>}
       </>
     );
   },
 });

5、v-for无法直接使用,需使用map去实现循环遍历渲染。

import { defineComponent, reactive } from "vue";
export default defineComponent({
   name: "HelloWorld",
   setup() {
     const list = reactive([1, 2, 3]);
     return () => (
       <>
         {list.map(item => (
           <h1>值为:{item}</h1>
         ))}
       </>
     );
   },
 });

6、v-on无法直接使用,需使用原生绑定事件方式去实现,因此无法使用事件修饰符。

// 不需要传值 
 import { defineComponent, ref } from "vue";
 export default defineComponent({
   name: "HelloWorld",
   setup() {
     const myName = ref("~WEB前端~");
     const changName = () => {
       myName.value = "欢迎";
     };
     return () => (
       <>
         <button onClick={changName}>{myName.value}</button>
       </>
     );
   },
 });
  // 传值的写法(高阶函数)
 import { defineComponent, ref } from "vue";
 export default defineComponent({
   name: "HelloWorld",
   props: ["msg"],
   setup() {
     const myName = ref("~WEB前端~");
     const changName = value => {
       console.log("value", value);
       myName.value = "欢迎";
     };
     return () => (
       <>
         <button onClick={() => changName("欢迎")}>{myName.value}</button>
       </>
     );
   },
 });
 // 获取事件对象
 import { defineComponent, ref } from "vue";
 export default defineComponent({
   name: "HelloWorld",
   props: ["msg"],
   setup() {
     const myName = ref("~WEB前端~");
     const changName = (event, value) => {
       console.log("event", event);
       console.log("value", value);
       myName.value = "欢迎";
     };
     return () => (
       <>
         <button onClick={event => changName(event, "欢迎~")}>{myName.value}</button>
       </>
     );
   },
 });

7、 v-bind(需注意以下三点)
1、标签属性值如果需要一个变量,需要按照 属性名={变量名} 的形式书写,并且属性名前不能带 “:” ;
2、如果是ref包装之后的响应式变量,需要按照 属性名={变量名.value} 的形式书写;
3、图片资源需先导入后使用,如下示例中的logo图片资源,

 import { defineComponent, ref } from "vue"
 import Logo from "./assets/logo.png"
 export default defineComponent({
     setup() {
         const altText = ref("Vue logo")
         return () => {
             <img alt={ altText.value } src={ Logo } />
         }
     }
 })

8、v-model

import { defineComponent, ref } from "vue";
export default defineComponent({
   name: "HelloWorld",
   setup() {
     const text = ref("WEB前端~");
     return () => (
       <>
         <h1>{text.value}</h1>
         <input v-model={text.value} placeholder="~WEB前端~" />
       </>
     );
   },
 });

9、v-slot,在jsx中v-slot,需要写成v-slots

 // HelloWorld.jsx
 import { defineComponent, ref } from "vue";
 export default defineComponent({
   name: "HelloWorld",
   props: ["msg"],
   setup(props, { slots }) {
     return () => (
       <>
         <h1>{slots.default ? slots.default() : "WEB前端"}</h1>
         <h2>{slots.bar?.()}</h2>
       </>
     );
   },
 });

第一种:

 // App.jsx
import { defineComponent } from "vue";
import HelloWorld from "./components/HelloWorld.jsx";
export default defineComponent({
  name: "App",
  components: { HelloWorld },
  setup() {
    const slots = {
      bar: () => <span>这个会渲染到h2中</span>,
    };
    return () => (
      <>
        <HelloWorld v-slots={slots}>
          <div>这个会渲染到H1中</div>
        </HelloWorld>
      </>
    );
  },
});

第二种:

 // App.jsx

 import { defineComponent } from "vue";
 import HelloWorld from "./components/HelloWorld.jsx";
 export default defineComponent({
   name: "App",
   components: { HelloWorld },
   setup() {
     const slots = {
       default: () => <div>这个会渲染到H1中</div>,
       bar: () => <span>这个会渲染到h2中</span>,
     };
     return () => (
       <>
         <HelloWorld v-slots={slots} />
       </>
     );
   },
 });

第三种:

 // App.jsx

 // h1当中渲染子组件默认的
 // h2当中则渲染父组件传入的bar组件内容
 import { defineComponent } from "vue";
 import HelloWorld from "./components/HelloWorld.jsx";

 export default defineComponent({
   name: "App",
   components: { HelloWorld },
   setup() {
     const slots = {
       bar: () => <span>这个会渲染到h2中</span>,
     };
     return () => (
       <>
         <HelloWorld v-slots={slots} />
       </>
     );
   },
 });

10、v-pre、v-cloak、v-once、v-memo 四个指令暂时未研究出来如何在jsx中去实现,欢迎补充。

第五部分、安装组件库(以Naive UI为例)
一、使用 pnpm安装naive-ui依赖

$ pnpm install naive-ui

1
二、建议按需引入,在使用组件库组件时,标签名应采用大驼峰式书写格式

 import { defineComponent, ref } from "vue";
 import { NButton } from "naive-ui";
 export default defineComponent({
   name: "HelloWorld",
   props: ["msg"],
   components: { NButton },
   setup() {
     const myName = ref("~WEB前端~");
     const changName = (event, value) => {
       console.log("event", event);
       console.log("value", value);
       myName.value = "~WEB前端~";
     };
     return () => (
       <>
         <NButton type="primary" onClick={event => changName(event, "~WEB前端~")}>
           {myName.value}
         </NButton>
       </>
     );
   },
 });

至此如何在vue中使用jsx语法内容全部讲完!!!

有关vue3 + tsx 的几种写法(完整版)的更多相关文章

  1. 计算机毕业设计ssm+vue基本微信小程序的小学生兴趣延时班预约小程序 - 2

    项目介绍随着我国经济迅速发展,人们对手机的需求越来越大,各种手机软件也都在被广泛应用,但是对于手机进行数据信息管理,对于手机的各种软件也是备受用户的喜爱小学生兴趣延时班预约小程序的设计与开发被用户普遍使用,为方便用户能够可以随时进行小学生兴趣延时班预约小程序的设计与开发的数据信息管理,特开发了小程序的设计与开发的管理系统。小学生兴趣延时班预约小程序的设计与开发的开发利用现有的成熟技术参考,以源代码为模板,分析功能调整与小学生兴趣延时班预约小程序的设计与开发的实际需求相结合,讨论了小学生兴趣延时班预约小程序的设计与开发的使用。开发环境开发说明:前端使用微信微信小程序开发工具:后端使用ssm:VU

  2. (附源码)vue3.0+.NET6实现聊天室(实时聊天SignalR) - 2

    参考文章搭建文章gitte源码在线体验可以注册两个号来测试演示图:一.整体介绍  介绍SignalR一种通讯模型Hub(中心模型,或者叫集线器模型),调用这个模型写好的方法,去发送消息。  内容有:    ①:Hub模型的方法介绍    ②:服务器端代码介绍    ③:前端vue3安装并调用后端方法    ④:聊天室样例整体流程:1、进入网站->调用连接SignalR的方法2、与好友发送消息->调用SignalR的自定义方法 前端通过,signalR内置方法.invoke()  去请求接口3、监听接受方法(渲染消息)通过new signalR.HubConnectionBuilder().on

  3. vue 实现内容超出两行显示展开更多功能,可依据需求自定义任意行数! - 2

    平时开发中我们经常会遇到这样的需求,在一个不限高度的盒子中会有很多内容,如果全部显示用户体验会非常不好,所以可以先折叠起来,当内容达到一定高度时,显示展开更多按钮,点击即可显示全部内容,先来看看效果图: 这样做用户体验瞬间得到提升,接下来看看具体细节。0">主要操作在内容这里{{item.username}},……展开更多样式大家可依据自己项目需求进行设计,这里就不贴了,主要说几个关键的。1、在data中定义三个属性isShowMore:false, //控制展开更多的显示与隐藏textHeight:null, //框中内容的高度status:false, //内容状态是否打开2.计算内容是否

  4. Ruby跨平台EOF符号的写法 - 2

    在Ruby中是否有一种平台无关的方式将EOF符号写入字符串。在*nix中,我认为符号是^D,但在Windows中是^Z,这就是我问的原因。 最佳答案 EOF不是一个字符,它是一个状态。终端使用控制字符来表示此状态(C-d)。没有这样的事情是“读一个EOF字符”,写一个也是一样的。如果您正在写入文件,请在完成后将其关闭。看这个mailinglistpost:ItsoundslikeyouarethinkingofEOFasanin-bandbutspecialcharactervaluethatmarkstheendoffile.It

  5. ruby-on-rails - 更好的写法 @instances.count > 0 - 2

    我有这个代码:0%>#@statesisanactiverecordcollection我只是觉得应该有更好的方式来写这个。我正在寻找类似的东西:我意识到这是一个微小的变化,但它会是一个受欢迎的清理。 最佳答案 您可能需要ActiveRecord的any?http://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-any-3FDostuffhereif@stateshasatleastoneresult 关

  6. vue3.0 + vite2.0+如何兼容低版本浏览器 - 2

    这里写自定义目录标题一、问题二、解决三、解决方案四、打包预览一、问题在使用vue3.2和vite2开发一个移动端或者钉钉端H5微服务iosapp内置浏览器打开没问题安卓app内置浏览器打开空白页面vconsole打印出现报错globalthisundefind二、解决内置浏览器版本比较低打印出来是63vue3代码不兼容低版本浏览器三、解决方案步骤一:vite.config.ts里build.target配置项指定构建目标为es2015或者步骤二:安装@vitejs/plugin-legacy安装完报错也还在指定版本可以解决“@vitejs/plugin-legacy”:“1.8.0”,步骤三:

  7. Vue3的新特性 - 2

    Vue3的新特性包括:CompositionAPI:一种新的API风格,可将有关组件功能的代码逻辑封装在单独的函数中,从而更好地管理和重用代码。Teleport:可以让组件在DOM层次结构中的任何位置渲染。Suspense:一种新的异步渲染模式,可以优化应用程序的性能。更快的渲染速度:Vue3使用了新的虚拟DOM算法,并且对渲染过程进行了优化,因此在渲染大型应用时性能更高。更小的包大小:Vue3的打包大小比Vue2更小,因为它不再需要依赖像vue-template-compiler这样的工具。其他改进:Vue3还具有其他一些改进,例如更好的TypeScript支持、更好的错误提示和更好的调试工

  8. vue2+element-ui,el-aside侧边栏容器收缩与展开 - 2

    一、概览实现效果如下:二、项目环境1、nodejs版本node-vv16.16.02、npm版本npm-vnpmWARNconfigglobal`--global`,`--local`aredeprecated.Use`--location=global`instead.8.15.03、vue脚手架版本vue-V@vue/cli5.0.8三、创建vue项目1、创建名为vuetest的项目vuecreatevuetest选择Default([Vue2]babel,eslint)  2、切换到项目目录,启动项目cdvuetestnpmrunserve 3、使用浏览器预览 http://localh

  9. Vue学习笔记:Vue element-ui中table组件的使用----接入后端数据 - 2

    记个笔记以免遗忘,建议还是查看Element-UI提供的官方文档学习,自己摸索比较难受官方文档:Element-UI组件TableElement-UI官网提供了许多Table格式,这里以一个带有筛选器的表格为例表格的官网显示效果:直接将官方提供的示例代码贴入.vue文件中即可使用显示的数据是通过data()方法提供的假数据。方法见下:data(){return{tableData:[{date:'2016-05-02',name:'王小虎',address:'上海市普陀区金沙江路1518弄'},{date:'2016-05-04',name:'王小虎',address:'上海市普陀区金沙江路1

  10. ruoyi-vue 新建模块--若依前后端分离系统代码生成。 - 2

    目录:1.在数据库中创建表2.使用代码生成功能,生成基础代码2.1修改代码生成器中配置文件generator.yml2.2使用系统工具代码生成3.新建子模块,迁移代码3.1创建grayskyax-assetsmanagement模块3.2在RuoYi整个项目下的`pom.xml`中引入刚刚新建的模块:3.3在ruoyi-admin模块的pom.xml中引入新建的模块3.4在新建的assetsManagement模块中引入ruoyi-common模块3.5将之前解压后的文件放如项目的对应目录下;3.6在数据库中执行生成的sql脚本3.7配置扫描路径application.yml,applicat

随机推荐