vue3Jsx使用

1. 安装依赖

  npm i @vitejs/plugin-vue-jsx -D

2. vite.config.js 配置

  import vue from '@vitejs/plugin-vue'
  import vueJsx from '@vitejs/plugin-vue-jsx'

  export default defineConfig({
    plugins: [
      vue(),
      vueJsx({
        // .js结尾的文件,支持jsx语法
        include: [/\.js$/]
      })
    ]
  })

3. 使用 defineComponent

  export default defineComponent({
    name: 'MyJsx',
    props: {
      msg: {
        type: String,
        default: 'Hello Jsx'
      }
    },
    setup(props, ctx) {
      return () => (
        <div>
          <h1 
            {/* 添加事件 */}
            onclick={() => console.log('click')}
          >
            MyJsx
          </h1>
          <h2 
            {/* 添加 emit 事件传递 */}
            onclick={() => ctx.emit('click')}
          >
            {/* 变量需用{}包裹 */}
            { props.msg }
          </h2>
        </div>
      )
    }
  })

  // 推荐写法 有props提示
  ![alt text](image.png)
  export default defineComponent((props, ctx) => {

    return () => (
      <div>
        <h1 onClick={() => console.log('点击了')}>{props.msg}</h1>
        <h2 
          onClick={() => ctx.emit('clickEvent')}
        >
          哈哈哈
        </h2>
      </div>
    )
  },
  {
    props: {
      msg: {
        type: String,
        default: '按钮'
      }
    }
  })

4. v-for 循环

  { list.map(e => <span :key={e}>{e}</span>)}

5. v-on 事件

  // 对于需要修饰符的事件,需要使用驼峰写法将他们拼接在事件名后面,例如 onClickCapture
  <div onClick={event => {}}>
    按钮
  </div>

6. v-if

  {isShow ? <div>显示</div> : null}

7. 插槽

  // 默认插槽 
  <div>
    {ctx.slots.default?.()}
  </div>

  <children>
    <div>这是从父组件传入的默认插槽内容</div>
  </children>

  // 具名插槽
  <div>
    {/* 
      list 为传递的参数 
      footer 为插槽名称
    */}
    {ctx.slots.footer?.({list})}
  </div>
  
  <children>
    <template v-slot:footer="{ list }">
      <div>
        这是从父组件传入的具名插槽footer
        {{  list  }}
      </div>
    </template>
  </children>

8. 添加样式

  // 使用 css 模块 注意文件后缀 .module.css
  import style from "@/assets/jsx.module.css";
  <p className={style.textRed}>通过css模块添加样式</p>

  // 行内样式
  <p style={{color: 'blue'}}>通过行内添加样式</p>

  // @styils/vue 插件 

  npm i @styils/vue

  import { styled } from "@styils/vue";

  {/* 
    参数一: html 标签
    参数二: 样式对象
   */}
  const MyStyledComponent = styled('div', {
    border: '1px solid seagreen',
    backgroundColor: 'violet',
    width: '100px',
    height: '100px',
    textAlign: 'center',
    lineHeight: '100px'
  })

  // 使用 
  return () => (
    <MyStyledComponent>
      使用styled
    </MyStyledComponent>
  )
posted @   加利福尼亚的阳光  阅读(127)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 展开说说关于C#中ORM框架的用法!
点击右上角即可分享
微信分享提示