戳蓝字"

Web前端严选

"

关注我们哦

前言

初衷: 前几天我在公司其它Vue项目中,发现了是用Decorator装饰器模式开发的,看起来整体代码还不错,于是就做了一下笔记分享给大家,不喜勿喷。

本项目是使用jsDecorator装饰器搭建,如果大家项目用的是ts,那么使用装饰器方法跟本文介绍的不同,请自行参考ts 使用装饰器。需要注意的是,使用这种模式,变量会存在污染,所以不能出现重名变量。

什么是Decorator

Decorator装饰器是一种类class相关的语法,所以Decorator装饰器只能用在class类里面,在普通的语法或表达式上不能使用。个人理解:装饰器可以给我们提供一层拦截的作用,先执行装饰器里面的东西,后执行我们的操作。具体请看阮一峰老师的《装饰器》。

安装

组件

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

配置

在项目的根目录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中常用的几个方法,具体详细的可以看这里Vue-property-decorator

生命周期、methods、data

这些写法都跟原来一样,直接写就行,看如下案例对比

原写法

<script>
export default {data() {return {msg: "hello 蛙人"}},created() {},methods: {test() {}}
}
</script>

装饰器写法

<script>
import { Vue } from 'vue-property-decorator'
class App extends Vue {msg = "hello 蛙人"created() {}test() {}
}
export default App
</script>

Emit

原写法

<script>
export default {methods: {send() {this.$emit("custom", 123)}}
}
</script>

装饰器写法

<script>
import { Vue, Emit } from 'vue-property-decorator'
class Hello extends Vue {created() {this.send()}@Emit("custom")send() {return 123}
}
export default Hello
</script>

Provide

原写法

<script>
export default {provide() {return {msg: this.msg}}
}
</script>

装饰器写法

<script>
class App extends Vue {@Provide() msg = this.msgmsg = "hello 蛙人"
}
export default App
</script>

Inject

原写法

export default {inject: {msg: {default: () => "",required: true} }
}
</script>

装饰器写法

import { Vue, Component,Inject } from 'vue-property-decorator'
@Component
class Hello extends Vue {@Inject({ required: true, default: () => "" }) msg
}
export default Hello

Prop

原写法

<script>
export default {props: {msg: {type: () => String,required: true}}
}
</script>

装饰器写法

<script>
import { Vue, Prop } from 'vue-property-decorator'
class Hello extends Vue {@Prop({ required: true, type: String }) msg
}
export default Hello
</script>

PropSync

原写法

// 父组件
<HelloWorld :msg.sync="msg" v-show="msg"/>// 子组件
<script>
export default {props: {msg: {require: true}},created() {setTimeout(() => {this.test()}, 5000)},methods: {test() {this.$emit("update:msg", false)}}
}
</script>

装饰器写法

@PropSync第一个参数则是,this.$emit("update:msg")里面的msg, 语句后面则跟着变量

<script>
import { Vue, Component, PropSync } from 'vue-property-decorator'
@Component
class Hello extends Vue {@PropSync("msg", { required: true }) variablecreated() {setTimeout(() => {this.variable = false}, 5000)}
}
export default Hello
</script>

Watch

原写法

export default {data() {return {str: 123  }},created() {setTimeout(() => {this.str = 12}, 5000)},watch: {str: function(newVal, oldVal) {console.log(newVal, oldVal)}}
}
</script>

装饰器写法

import { Vue, Component, Watch } from 'vue-property-decorator'
@Component
class Hello extends Vue {str = 123created() {setTimeout(() => {this.str = 12}, 2000)}@Watch("str", {deep: true})test(newVal, oldVal) {console.log(newVal, oldVal)}
}
export default Hello

Computed

原写法

<script>
export default {computed: {test: {get() {return this.msg},set(val) {return this.msg = val}}}
}
</script>

装饰器写法

<script>
import { Vue, Component } from 'vue-property-decorator'
@Component
class App extends Vue {get test() {return this.msg}set test(val) {return this.msg = val}}
export default App

Model

有时候我们想给组件写一个v-model方法就可以这样,如下

原写法

// 父组件
<HelloWorld :msg="msg" v-model="msg"/>// 子组件
<input type="text" @input="test" :value="msg"><script>
export default {props: {msg: {require: true}},model: {prop: "msg",event: "input"},methods: {test(e) {this.$emit("input", e.target.value)}}
}
</script>

装饰器写法

// 父组件
<HelloWorld :msg="msg" v-model="msg"/>// 子组件
<input type="text" @input="test" :value="msg"><script>
import { Vue, Component, Model, Emit } from 'vue-property-decorator'
@Component
class Hello extends Vue {@Model("input", {default: () => ""}) msgtest(e) {this.send(e)}@Emit("input")send(e) {return e.target.value}
}
export default Hello
</script>

Ref

原写法

<HelloWorld :msg="msg" ref="val"/><script>
export default {name: 'App',components: {HelloWorld},data() {return {msg: "hello 蛙人"}},mounted() {console.log(this.$refs.val)},
}
</script>

装饰器写法

<HelloWorld :msg="msg" ref="val"/><script>
import { Vue, Component, Ref } from 'vue-property-decorator'
@Component({components: {HelloWorld}
})
class App extends Vue {@Ref("val") valmsg = "hello 蛙人"mounted() {console.log(this.val)}
}
export default App
</script>

Component

该方法是从组件库中导入,如果使用使用生命周期方法,记得引入此装饰器,否则不生效。该装饰器接收一个对象里面也可以写原生Vue方法。

<script>
import { Vue, Component } from 'vue-property-decorator'
@Component({components: {},watch: {str: function(val) {console.log(val)}}
})
export class App extends Vue {}
</script>

扩展

当然了可以根据自己的需求扩展封装Decorator装饰器,装饰器接收三个参数

  • 目标对象

  • 目标key

  • 描述对象

这里不明白描述对象属性可以看这篇文章《深入理解JavaScript对象》

<script>
function Decorator(data) {return (vue, key, describe) => {// vue 当前执行环境对象// key 当前装饰器函数对象 test// describe 描述对象里面value是函数let fn = describe.valuedescribe.value = function () {let status = window.confirm(data)if (status) return fn()}}
}
import { Vue, Component } from 'vue-property-decorator'
@Component
class App extends Vue {@Decorator("请点击确定")test() { window.confirm("你是否完成了")}
}
export default App
</script>

上面example中,可扩展自己的Decorator装饰器,装饰器就相当于起一层拦截作用,先执行装饰器里面的操作,在执行我们函数本身的逻辑操作。我这里只做一个案例哈,具体看你们的需求。

感谢

❤️ 感谢大家

如果你觉得这篇内容对你挺有有帮助的话:

  1. 看到这里了就点个在看支持一下吧,你的[在看]是我创作的动力;

  2. 关注公众号【Web前端严选】,进交流群,定期为你推送好文。

添加个人微信,进群与小伙伴一起玩耍(已经推出)~

聊聊在Vue项目中使用Decorator装饰器相关推荐

  1. Python中的decorator装饰器使用方法

    装饰器的运用是Python编程中的一项高级技巧,这里由浅入深,整理了12步入门Python中的decorator装饰器使用方法,需要的朋友可以参考下 装饰器(decorator)是一种高级Python ...

  2. 在vue项目中引用萤石云播放器插件

    在vue项目中引用萤石云播放器插件 1. 萤石云官方开发文档: https://open.ys7.com/help/31 2. 登录官方网站:https://open.ys7.com/cn/s/ind ...

  3. vue项目中 axios请求拦截器与取消pending请求功能 - 年少、 - 博客园

    在开发vue项目中,请求是不可缺少的,在发送请求时常常需要统一处理一些请求头参数等设置与响应事件,这时利用请求拦截器再好不过. 这里以axios请求为例 实现了设置统一请求头添加token, 其中to ...

  4. 在vue项目中使用阿里云播放器

    在官方文档中分为HTML5和Flash两种播放模式我用的是html5的播放模式,下面是阿里云官方文档 阿里云播放器的使用说明_视频点播-阿里云帮助中心 首先在index.html文件中引入 <l ...

  5. Vue项目中使用图片裁切器 cropperjs (头像裁切)

    cropperjs官方文档 cropperjs结合element-ui 组件后的显示效果: 1. npm 安装 cropperjs cmd命令行输入:npm install cropperjs --s ...

  6. 一文读懂 @Decorator 装饰器——理解 VS Code 源码的基础

    作者:easonruan,腾讯 CSIG 前端开发工程师 1. 装饰器的样子 我们先来看看 Decorator 装饰器长什么样子,大家可能没在项目中用过 Decorator 装饰器,但多多少少会看过下 ...

  7. Typescript在Vue项目中的使用

    最近尝试了一下Typescript在Vue项目中的使用,中间遇到了一些问题,把遇到的问题记录一下,以防被忘. 如何让Typescript识别Vue.JSON文件 因为Typescript默认不能识别. ...

  8. TypeScript深度剖析:Vue项目中应用TypeScript?

    一.前言 与link类似 在VUE项目中应用typescript,我们需要引入一个库vue-property-decorator, 其是基于vue-class-component库而来,这个库vue官 ...

  9. 如何在Vue项目中应用TypeScript?

    一.前言 在VUE项目中应用typescript,我们需要引入一个库vue-property-decorator, # npm 下载 npm i vue-property-decorator -s # ...

最新文章

  1. poj 1815 Friendship 最小割 拆点 输出字典序
  2. Python的numpy库中rand(),randn(),randint(),random_integers()的使用
  3. [YTU]_2536( C++ 长方体继承自矩形)
  4. Zookeeper C API 指南
  5. Java 8的方法参考进一步限制了重载
  6. hdoj4283 You Are the One
  7. ASP.NET调用Oracle分页存储过程并结合ASPnetpager分页控件 实现分页功能
  8. RGB数据保存为BMP图片
  9. python横向输出字符串_Python字符串及用法详解
  10. Axure rp 9 的汉化破解版
  11. 前端实现导入(excel文件)导出(word)文件
  12. gitlab多人协同工作
  13. JDK7官方下载地址
  14. CentOS7.6腾讯云中域名的备案详细流程
  15. Mysql eighth week
  16. 企业微信Windows版本调试
  17. oracle 的concat()函数,Oracle Concat()函数
  18. php的mssql_connect+端口连接不了的问题
  19. Accepted Necklace HDU - 2660
  20. python 异步加载图片_Python 爬取拉钩网异步加载页面

热门文章

  1. MOS管工作原理的应用驱动电路详解
  2. iOS平台epub阅读器推荐
  3. Linux 基金会发布《开源软件供应链安全报告》
  4. 可爱儿童卡通PPT模板推荐
  5. java response下载docx,报文件损坏是否修复,ContentLength导致的
  6. 自考——操作系统概论
  7. Javaweb day05
  8. excel批量提取超链接
  9. 【源码篇】安卓源码解析(持续总结)
  10. 使用XSHELL连接中标麒麟系统