Vue3支持使用JSX语法来编写模板,可以通过以下步骤来使用JSX:

  1. 安装依赖

安装@vue/babel-plugin-jsx和@vue/compiler-sfc依赖:

npm install @vue/babel-plugin-jsx @vue/compiler-sfc --save-dev
  1. 配置babel

在.babelrc或babel.config.js中配置@vue/babel-plugin-jsx插件:

module.exports = {
  presets: [
    // ...
  ],
  plugins: [
    // ...
    "@vue/babel-plugin-jsx"
  ]
}
  1. 创建Vue组件

使用defineComponent函数创建Vue组件:

import { defineComponent } from 'vue';

export default defineComponent({
  props: {
    name: {
      type: String,
      required: true
    }
  },
  render() {
    return <div>Hello, {this.name}!</div>
  }
});
  1. 在Vue应用中使用组件

在Vue应用中使用JSX编写的组件:

<template>
  <div>
    <MyComponent name="Vue3" />
  </div>
</template>

<script>
import MyComponent from './MyComponent';

export default {
  components: {
    MyComponent
  }
}
</script>

以上就是Vue3使用JSX的基本方法。需要注意的是,JSX语法需要先转换成VNode才能被Vue渲染,因此需要使用@vue/compiler-sfc提供的compile函数将JSX代码编译成render函数,然后再在组件中使用render函数渲染。

vue3 JSX 使用方法

原文地址: https://www.cveoy.top/t/topic/bYoW 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录