前言
前排警告,這不是玩具!
那、還能是啥呢
起因
最近看到好多在Vue中使用JSX的文章,作為目前最受歡迎的MVVM框架,其實不學習還是有些對不住自己的。但是無奈太喜歡React,所以在Vue中能使用JSX還是能勾起很多人的好奇心的。
我就是,還有么
簡單Demo
對於vue-cli3和4創建的Vue工程,是可以直接使用JSX語法的,簡單的就是template刪除了,寫個render,其他的就和寫React類組件差不多了。
嗎😢?
還是沒那么簡單的,不過可以先看個簡單的傳值:
<script> import HelloWorld from "@/components/HelloWorld.vue"; export default { name: "home", render() { return <HelloWorld msg="this is helloworld" />; } }; </script>
<script> export default { name: "HelloWorld", props: { msg: String }, render() { return <div>{this.msg}</div>; } }; </script> <style scoped lang="less"> div { margin: 40px; } </style>
關於JSX
如果上面的示例對你沒什么難度,以React的角度來說。那么我們就來看一下加上Vue的角度的一些基本的東西:
<script> import HelloWorld from "@/components/HelloWorld.vue"; export default { name: "home", data() { return { data: [12, 34, 56] }; }, methods: { handleClick() { console.log(123); } }, render() { return ( <div> <button onClick={this.handleClick}>click</button> <HelloWorld msg="this is helloworld" /> <ul> {this.data.map(i => ( <li key={i}>{i}</li> ))} </ul> </div> ); } }; </script>
傳事件
<HelloWorld msg="this is helloworld" handleClick={this.handleClick} /> <script> export default { name: "HelloWorld", props: { msg: String, handleClick: Function }, render() { return ( <div> <button onClick={this.handleClick}>click</button> <div>{this.msg}</div> </div> ); } }; </script>
因為不會有React處理事件時解析語法this指向取消的問題,所以這里也不需要bind。
生命周期
Vue的生命周期很條理:
beforeCreate, created
beforeMount, mounted
beforeUpdate, updated
beforeDestroy, destroyed
這部分和JSX關系不大,
Vue-Router <div id="app"> <div id="nav"> <router-link to="/">Home</router-link> | <router-link to="/about">About</router-link> </div> <router-view /> </div>
App.vue同樣可以做這樣的修改,使得我們以JSX的方式引入路由。
同時我們也可以混用template和JSX。
總結
只是簡單的Demo,已經可以在遷移量不大的情況下做出一些東西了,后續會結合Vuex和Vue-router寫點東西熟悉一下。
————————————————
版權聲明:本文為CSDN博主「eswang」的原創文章,遵循 CC 4.0 BY-SA 版權協議,轉載請附上原文出處鏈接及本聲明。
原文鏈接:https://blog.csdn.net/weixin_43870742/java/article/details/104255946