- 我猜你可能是一个更偏向于个
React开发者 - 我猜你可能深深的感受到了
Hooks带来的逻辑复用、响应式编程的种种便利 - 我猜你可能深度依赖
Typescript,又很喜欢JSX的强大表现力 - 我估计你公司用的
Vue2,虽然出了Vue3可以用上面种种好处;可是你还得维护Vue2老项目 - 我估计你心里很不爽,又想学习
Vue3带来新特性,又想重构已有Vue2项目但是成本太大 - 我估计你再这么下去,可能是想跑路了都~ 👻
- ...
- 目的 本文是从
React使用者视角带你解锁Vue2中开启Composition API🖖 并使用TSX🚀 地开发模式 🎉 - 希望 本文能助你一臂之力 💪 不要慌,你还可以继续治疗 💊
- 使用
Vue2工程模板加入Composition API插件 - 开启
.ts、.tsx支持
略~
- 添加依赖
yarn add @vue/composition-api本项目使用的 Babel@7.x
-
添加依赖
yarn add -D @vue/babel-preset-jsx @vue/babel-helper-vue-jsx-merge-props @babel/plugin-transform-typescript
-
修改配置文件
-
修改根目录
babel.config.jsmodule.exports = { presets: [ '@vue/cli-plugin-babel/preset', + ['@vue/babel-preset-jsx', { compositionAPI: true }], // 开启 jsx ], + plugins: [ + ['@babel/plugin-transform-typescript', { isTSX: true }], // 开启 typescript + ], } -
根目录新建
vue.config.js+ const path = require('path') + module.exports = { + configureWebpack: { + resolve: { + alias: { + '@': path.resolve(__dirname, './src'), + }, + extensions: ['.ts', '.tsx'], + }, + module: { + rules: [ + { + test: /\.(jsx|tsx|ts)$/, + loader: 'babel-loader', + }, + ], + }, + }, + }
-
根目录新建
tsconfig.json+ { + "compilerOptions": { + "target": "ES2017", + "module": "UMD", + "allowJs": true, + "jsx": "preserve", + "moduleResolution": "Node", + "allowSyntheticDefaultImports": true, + "importHelpers": true, + "baseUrl": "./", + "paths": { + "@/*": ["src/*"] + } + } + }
-
-
.vue文件和.tsx可以看成是等价的,直接使用即可;注意jsx中组件标签首字母一定要大写 😄 -
.png静态资源用法就是直接引入,底层通过url-loader处理;@vue/cli 集成了静态资源配置import { defineComponent, onMounted } from '@vue/composition-api' import HelloWorld from './components/HelloWorld.vue' import logo from '@/assets/logo.png' export default defineComponent({ setup() { onMounted(() => {}) }, render() { return ( <div class="app"> <img alt="Vue logo" src={logo} /> <HelloWorld msg="Welcome to Your Vue.js App"/> </div> ) }, })
-
注意!
setup中不支持 (setup 中没有 this)tsx, 必须写在render中 -
启动下项目看看效果吧~
yarn serve

