0
点赞
收藏
分享

微信扫一扫

国内用ChatGPT可以吗

陆佃 2024-03-08 阅读 27

前言

初衷

探索Vue项目中装饰器模式的使用,发现它能显著提升代码的整洁性。以下内容基于个人学习笔记,旨在分享装饰器在Vue 2中的应用。适合初级前端开发者阅读和参考。

注意事项

本文介绍基于JavaScript的装饰器使用。TypeScript用户需要适当调整以适用于TypeScript的装饰器语法。使用装饰器模式时,要注意避免变量命名冲突。

装饰器(Decorator)简介

装饰器提供一种在类执行前后添加额外逻辑的语法,主要用于类及其成员的声明处理。

环境准备

安装依赖

npm install --save vue-class-component
npm install --save vue-property-decorator

配置babeljsconfig

  • babel.config.js:
module.exports = {
  presets: ['@vue/app'],
  plugins: [
    ['@babel/plugin-proposal-decorators', { legacy: true }],
    ['@babel/plugin-proposal-class-properties', { loose: true }],
  ]
};
  • jsconfig.json:
{
  "compilerOptions": {
    "experimentalDecorators": true
  }
}

使用装饰器

以下是Vue 2中一些常见功能的传统写法与装饰器写法的对比。

生命周期、methods、data

  • 原写法
export default {
  data() {
    return {
      msg: "hello 蛙人"
    };
  },
  created() {
    
  },
  methods: {
    test() {
      
    }
  }
};
  • 装饰器写法
import { Vue } from 'vue-property-decorator';
class App extends Vue {
  msg = "hello 蛙人";
  created() {
    
  }
  test() {
    
  }
}
export default App;

Emit

  • 原写法
export default {
  methods: {
    send() {
      this.$emit("custom", 123);
    }
  }
};
  • 装饰器写法
import { Vue, Emit } from 'vue-property-decorator';
class Hello extends Vue {
  @Emit("custom") send() {
    return 123;
  }
}
export default Hello;

Provide & Inject

  • 原写法
export default {
  provide() {
    return {
      msg: this.msg
    };
  }
};
  • 装饰器写法
import { Vue, Provide, Inject } from 'vue-property-decorator';
class App extends Vue {
  @Provide() msg = "hello 蛙人";
}
class Hello extends Vue {
  @Inject() readonly msg;
}

Prop & PropSync

  • 原写法
export default {
  props: {
    msg: {
      type: String,
      required: true
    }
  }
};
  • 装饰器写法
import { Vue, Prop, PropSync } from 'vue-property-decorator';
class Hello extends Vue {
  @Prop({ required: true, type: String }) msg;
}

Watch

  • 原写法
export default {
  data() {
    return {
      str: 123  
    };
  },
  watch: {
    str(newVal, oldVal) {
      console.log(newVal, oldVal);
    }
  }
};
  • 装饰器写法
import { Vue, Watch } from 'vue-property-decorator';
class Hello extends Vue {
  str = 123;
  @Watch("str") onStrChange(newVal, oldVal) {
    console.log(newVal, oldVal);
  }
}

通过这些对比,我们可以看到装饰器写法使得组件代码更加简洁明了,尤其是在定义复杂组件和高级功能时,装饰器提供了更优雅的代码组织方式。

举报

相关推荐

0 条评论