如果我们希望在项目中使用jsx,那么我们需要添加对jsx的支持:
- jsx我们通常会通过Babel来进行转换(React编写的jsx就是通过babel转换的);
- 对于Vue来说,我们只需要在Babel中配置对应的插件即可;
webpack 中安装
- 安装Babel支持Vue的jsx插件:
npm install @vue/babel-plugin-jsx -D在babel.config.js配置文件中配置插件:
module.exports = {
presets:[
'@vue/cli-plugin-babel/preset'
],
plugins:[
"@vue/babel-plugin-jsx"
]
}
Vite环境
如果是Vite环境,需要安装插件:
npm install @vitejs/plugin-vue-jsx -D在vite.config.js配置文件中配置插件:
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vite'
import jsx from '@vitejs/plugin-vue-jsx' // 引入
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
jsx() // 使用
],
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url))
}
}
})
使用案例
基本使用
<script lang="jsx">
export default {
render() {
return (
<div class="app">
<h2>我是标题</h2>
<p>我是内容, 哈哈哈</p>
</div>
)
}
}
</script>
<style lang="less" scoped>
</style>
Options-Api中
<script lang="jsx">
import About from './About.vue'
export default {
data(){
return {
counter:0
}
},
render(){
return (
<div class="app">
<h2>当前计数:{this.counter}</h2>
<button onClick={this.increment}>+1</button>
<button onClick={this.decrement}>-1</button>
<About />
</div>
)
},
methods:{
increment(){
this.counter++
},
decrement(){
this.counter--
}
}
}
</script>
<style lang="less" scoped>
</style>Compitions-Api中
<template>
<jsx />
</template>
<script lang="jsx" setup>
import { ref } from 'vue'
import About from "./About.vue"
const counter = ref(0)
const increment = () => {
counter.value++
}
const decrement = () => {
counter.value--;
}
const jsx = () => (
<div>
<h2>当前计数:{ counter.value }</h2>
<button onClick={increment}> +1 </button>
<button onClick={decrement}> -1 </button>
<About />
</div>
)
</script>
<style lang="less" scoped>
</style>setup函数中使用
<script lang="jsx">
import { ref } from 'vue'
import About from './About.vue'
export default {
setup(){
const counter = ref(0)
const increment = () => {
counter.value++
}
const decrement = () => {
counter.value--
}
return () => (
<div class="app">
<h2>当前计数:{ counter.value }</h2>
<button onClick={increment}>+1</button>
<button onClick={decrement}>-1</button>
<About />
</div>
)
}
}
</script>
<style lang="less" scoped>
</style>感谢大家观看,我们下次见
It's not my first time to pay a visit this web page, i am visiting this website dailly and get good facts from here every day.
Hello, i think that i saw you visited my site so i got here to go back the want?.I'm trying to find things to improve my web site!I suppose its adequate to use a few of your concepts!!
Touche. Outstanding arguments. Keep up the great effort.
Wow, this post is good, my younger sister is analyzing these things, therefore I am going to let know her.
There's certainly a lot to learn about this topic. I like all the points you've made.
所有文章都令人印象深刻。由衷感谢 带来的灵感。
你 百分百 分享经验。坚持!
不常看到, 这么高质量的内容。谢谢。
@十二使徒岩 哪张图片?
照片令人惊艳。继续保持 心情。