console.log|

邪妖怪

园龄:2年3个月粉丝:2关注:5

📂Vue
🔖Vue
2024-10-31 16:29阅读: 231评论: 0推荐: 0

vue3 类组件装饰器模式配置

2024年10月31日

vue3 支持装饰器模式插件

借助插件vue-facing-decorator实现类组件装饰器转换

npm install --save-dev vue-facing-decorator @rollup/plugin-babel @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties

vite.config.ts配置

// 第一种 支持装饰器模式逻辑与模版写在同一个tsx文件内一起解析
import vueJsx from '@vitejs/plugin-vue-jsx'

export default defineConfig({
  plugins: [
    vueJsx({
      babelPlugins: [
        ["@babel/plugin-proposal-decorators", { "legacy": true }],
        ["@babel/plugin-proposal-class-properties", { "loose": true }]
      ]
    }),
  ]
})
// 第二种 支持装饰器模式逻辑与模版分离 进行解析
import vueJsx from '@vitejs/plugin-vue-jsx'

export default defineConfig({
  plugins: [
    babel({
      babelHelpers: 'bundled',
      extensions: ['.js', '.jsx', '.ts', '.tsx', '.vue'],
      plugins: [
        ["@babel/plugin-proposal-decorators", { "legacy": true }],
        ["@babel/plugin-proposal-class-properties", { "loose": true }]
      ]
    })
  ]
})

配置详解

两种配置对应的组件文件情况如下:

// 第一种 
// Comp.tsx
import { Component, toNative } from "vue-facing-decorator"

function render () {
  return <></>
}

@Component({
  render
})
class Comp extends Base {}

export default toNative(Comp)
// 第二种 
// Comp.render.tsx
import { Component, toNative } from "vue-facing-decorator"

export default function render () {
  return <></>
}

// Comp.ts
import { Component, toNative } from "vue-facing-decorator"
import render from "./Comp.render.tsx"

@Component({
  render
})
class Comp extends Base {}

export default toNative(Comp)

第二种tsx文件命名方式要重命名为Comp.xxxx.tsx,否则会报错,暂不知是何原因?

注意事项

1. 由于是类,使用此种模式尤其要注意this的指向问题
2. 涉及响应式赋值时,如果从this中解构类属性,插件转换后将失去响应性

本文作者:邪妖怪

本文链接:https://www.cnblogs.com/lastkiss/p/18518172

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   邪妖怪  阅读(231)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起