Vue3 支持 JSX 语法,通过使用 JSX,我们可以将组件和模板合并为一个概念。以下是使用 Vue3 的 JSX 的基本方法:

  1. 安装 @vue/babel-plugin-jsx 插件
npm install @vue/babel-plugin-jsx --save-dev
  1. babel.config.js 中配置插件
module.exports = {
  presets: [
    '@vue/cli-plugin-babel/preset'
  ],
  plugins: [
    '@vue/babel-plugin-jsx'
  ]
};
  1. 创建一个组件
import { defineComponent } from 'vue';

export default defineComponent({
  props: {
    title: {
      type: String,
      required: true
    },
    content: {
      type: String,
      required: true
    }
  },
  setup(props) {
    return () => (
      <div>
        <h1>{props.title}</h1>
        <p>{props.content}</p>
      </div>
    );
  }
});
  1. main.js 中使用组件
import { createApp } from 'vue';
import App from './App';

createApp(App).mount('#app');
  1. 在模板中使用组件
<template>
  <div id="app">
    <my-component title="Hello" content="World"></my-component>
  </div>
</template>

通过使用 JSX,我们可以更加直观地描述组件的结构和行为,使得代码更加易读易懂。

Vue3 JSX 使用指南:快速上手 JSX 语法

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

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