一篇文章带你使用Typescript封装一个Vue组件

Jacquelyn38
• 阅读 1923

搭建项目以及初始化配置

vue create ts_vue_btn  

这里使用了vue CLI3自定义选择的服务,我选择了ts、stylus等工具。然后创建完项目之后,进入项目。使用快捷命令code .进入Vs code编辑器(如果没有code .,需要将编辑器的「bin文件目录地址」放到环境变量的path中)。然后,我进入编辑器之后,进入设置工作区,随便设置一个参数,这里比如推荐设置字号,点下。这里是为了生成.vscode文件夹,里面有个json文件。一篇文章带你使用Typescript封装一个Vue组件

我们在开发项目的时候,项目文件夹内的文件很多,会有时影响视觉。那么这个文件就是设置什么文件隐藏,注意只是隐藏,而不是删除!下面是我自己写的,在「Vue cli3」生成的项目需要隐藏的文件参数。

{  
    "files.exclude": {  
        "**/.git": true,  
        "**/.svn": true,  
        "**/.hg": true,  
        "**/CVS": true,  
        "**/.DS_Store": true,  
        "**/README.md": true,  
        "**/node_modules":true,  
        "**/shims-tsx.d.ts": true,  
        "**/shims-vue.d.ts": true,  
        "**/.browserslistrc": true,  
        ".eslintrc.js": true,  
        "babel.config.js": true,  
        "package-lock.json": true,  
        ".gitignore": true,  
        "tsconfig.json": true  
    }  
}  

以下就是所看到的文件目录,我把一些无关紧要的文件跟文件夹隐藏或者删除后所看到的。一篇文章带你使用Typescript封装一个Vue组件文件解读(从上往下):

文件夹或文件 包含子文件夹或文件 含义
.vscode settings.json 隐藏文件设置
public index.html、favicon.ico 静态文件存放处
src components文件夹(存放组件)、App.vue、Home.vue、main.js 项目主要文件夹
package.json 项目依赖参数等

开发实践

下图为所需要创建的项目文件目录,这里我们开发一个Vue按钮组件。一篇文章带你使用Typescript封装一个Vue组件)如下图所示,这就是我们要用Typescript开发的组件。一篇文章带你使用Typescript封装一个Vue组件


开始编辑:
1、App.vue
<template>  
  <div id="app">  
   <Home></Home>   
  </div>  
</template>  

<script lang="ts">  
import { Component, Vue } from 'vue-property-decorator';// 编写类样式组件所需要的一些类或者是装饰器  
import Home from "@/Home.vue"; // 引入页面组件  

// 这里我们需要使用Component装饰器,这个装饰器是注册组件用的,里面的参数是一个对象,内有一个components属性,值为引入的组件名  
@Component({  
  components:{  
    Home  
  }  
})  
export default class App extends Vue {}  
</script>  

<style lang="stylus">  

</style>  

2、UIBtn.vue
<template>  
  <!-- v-on="$listeners" 可以使用,在本类不再监听,在其他地方监听,可以不用$emit(),但是我们这里不用它 -->  
  <button  
    class="ui-btn"  
    @click="onBtnclick('success!')"  
    :class="{  
    'ui-btn-xsmall':xsmall,  
    'ui-btn-small':small,  
    'ui-btn-large':large,  
    'ui-btn-xlarge':xlarge  
  }"  
  >  
    <slot>Button</slot>  
  </button>  
</template>  

<script lang="ts">  
import { Component, Vue, Emit, Prop } from "vue-property-decorator"; // 编写类样式组件所需要的一些类或者是装饰器  
@Component  
export default class UIBtn extends Vue {  
  @Prop(Boolean) private xsmall: boolean | undefined;  
  @Prop(Boolean) private small: boolean | undefined;  
  @Prop(Boolean) private large: boolean | undefined;  
  @Prop(Boolean) private xlarge: boolean | undefined;  
  // eslint-disable-next-line @typescript-eslint/no-empty-function  
  @Emit("click") private emitclick(x: string) {}  
  private mounted() {  
    console.log(this.large);  
  }  
  private onBtnclick(x: string) {  
    this.emitclick(x);  
  }  
}  
</script>  

<style scoped lang="stylus" >  
resize(a, b, c)   
  padding a b   
  font-size  c  
.ui-btn   
  resize(12px, 20px, 14px)  
  border 0 solid #000  
  border-radius 4px  
  outline none  
  font-weight 500;  
  letter-spacing 0.09em  
  background-color #409eff  
  color #fff  
  cursor pointer  
  user-select none  
  &:hover  
    filter brightness(120%)  
  &:active  
    filter brightness(80%)  
  &.ui-btn-xsmall   
    resize(5px, 15px, 14px)  
  &.ui-btn-small   
    resize(8px, 18px, 14px)  
  &.ui-btn-large   
    resize(14px, 22px, 14px)  
  &.ui-btn-xlarge   
    resize(16px, 24px, 14px)  
</style>  
3、Home.vue
<template>  
  <div class="home-con">  
      <div class="btn-group">  
           <UIBtn class="btn" @click="resize('xsmall')">超小</UIBtn>  
           <UIBtn class="btn" @click="resize('small')">小</UIBtn>  
           <UIBtn class="btn" @click="resize('normal')">正常</UIBtn>  
           <UIBtn class="btn" @click="resize('large')">大</UIBtn>  
           <UIBtn class="btn" @click="resize('xlarge')">超大</UIBtn>  
      </div>  
      <div class="btn-con">  
           <UIBtn @click='onClick'   
           :xlarge="xlarge"  
           :large="large"  
           :small="small"  
           :xsmall="xsmall"  
           >主要按钮</UIBtn>  
      </div>  
      <div class="btn-pro">  
            <UIBtn large >样式按钮</UIBtn>  
      </div>      
  </div>  
</template>  

<script lang="ts">  
import { Component, Vue } from 'vue-property-decorator'; // 编写类样式组件所需要的一些类或者是装饰器  
import UIBtn from '@/components/UIBtn.vue';  
@Component({  
    components:{  
      UIBtn  
    }  
})  
export default class Home extends Vue {  
   // eslint-disable-next-line @typescript-eslint/no-inferrable-types  
   private xlarge: boolean = false;  
    // eslint-disable-next-line @typescript-eslint/no-inferrable-types  
   private large: boolean = false;  
    // eslint-disable-next-line @typescript-eslint/no-inferrable-types  
   private xsmall: boolean = false;  
    // eslint-disable-next-line @typescript-eslint/no-inferrable-types  
   private small: boolean = false;  
   private resize (name: string){  
       console.log(name)  
       switch (name) {  
           case 'xsmall':  
               this.xsmall=true;  
               this.small=false;  
               this.large=false;  
               this.xlarge=false;  
               break;  
           case 'small':  
               this.xsmall=false;  
               this.small=true;  
               this.large=false;  
               this.xlarge=false;  
               break;  
           case 'normal':  
               this.xsmall=false;  
               this.small=false;  
               this.large=false;  
               this.xlarge=false;  
               break;  
           case 'large':  
               this.xsmall=false;  
               this.small=false;  
               this.large=true;  
               this.xlarge=false;  
               break;  
           case 'xlarge':  
               this.xsmall=false;  
               this.small=false;  
               this.large=false;  
               this.xlarge=true;  
               break;  
       }  
   }  
   private onClick(x: string) {  
       console.log(x)  
    }  
}  
</script>  

<style lang="stylus" scoped>.btn-group  
    margin 50px 0  
.btn  
    margin 6px  
.btn-pro  
    margin-top 50px </style>  

结语

作者:「Vam的金豆之路」

主要领域:「前端开发」

我的微信:「maomin9761」

微信公众号:「前端历劫之路」

一篇文章带你使用Typescript封装一个Vue组件

本文转转自微信公众号前端历劫之路原创https://mp.weixin.qq.com/s/7yVMIx2t4ErXdZTizY-TPw,如有侵权,请联系删除。

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Wesley13 Wesley13
2年前
35岁是技术人的天花板吗?
35岁是技术人的天花板吗?我非常不认同“35岁现象”,人类没有那么脆弱,人类的智力不会说是35岁之后就停止发展,更不是说35岁之后就没有机会了。马云35岁还在教书,任正非35岁还在工厂上班。为什么技术人员到35岁就应该退役了呢?所以35岁根本就不是一个问题,我今年已经37岁了,我发现我才刚刚找到自己的节奏,刚刚上路。
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这