vue-cli3构建TS项目(基础篇)

概述:
template 和 style 跟以前的写法保持一致,只有 script 的变化

Vue三个TS封装库
vue-class-component

vue-class-component 对 Vue 组件进行了一层封装,让 Vue 组件语法在结合了 TypeScript 语法之后更加扁平化
vue-property-decorator

vue-property-decorator 是在 vue-class-component 上增强了更多的结合 Vue 特性的装饰器,新增了这 7 个装饰器
vuex-class

1.通过vue-cli3生成项目

vue create xxx
1

注:安装时选择TypeScript之后,回自动安装vue-class-component,vue-property-decorator,具体见package.json文件


vue-cli3脚手架生成项目目录说明

│ .browserslistrc
│ .gitignore
│ .postcssrc.js // postcss 配置
│ babel.config.js
│ package.json // 依赖
│ README.md // 项目 readme
│ tsconfig.json // ts 配置
│ tslint.json // tslint 配置
│ vue.config.js // webpack 配置(~自己新建~)
│ yarn.lock
│ 
├─public // 静态页面
│ │—favicon.ico
│ │—index.html
│ 
├─src // 主目录
│ ├─assets // 静态资源
│ │ logo.png
│ │ 
│ ├─components
│ │ HelloWorld.vue
│ │ 
│ │─views // 页面
│ │ About.vue
│ │ Home.vue
│ │ 
│ │ App.vue // 页面主入口
│ │ 
│ │ main.ts // 脚本主入口
│ │ 
│ ├─router // 路由配置
│ │ index.ts
│ │ 
│ │ registerServiceWorker.ts // PWA 配置
│ │ 
│ │ shims-tsx.d.ts
│ │ shims-vue.d.ts
│ │ 
│ ├─filters // 过滤(~自己新建~)
│ ├─lib // 全局插件(~自己新建~)
│ │ 
│ │ 
│ ├─store // vuex 配置
│ │ index.ts
│ │ 
│ ├─typings // 全局注入(~自己新建~)
│ │ 
│ ├─utils // 工具方法(axios封装,全局方法等)(~自己新建~)
│ 
│ 
└─tests // 测试用例
├─e2e
│ ├─plugins
│ │ index.js
│ │ 
│ ├─specs
│ │ test.js
│ │ 
│ └─support
│ commands.js
│ index.js
│ 
└─unit
HelloWorld.spec.ts 



shims-vue.d.ts文件说明

注:由于 TypeScript 默认并不支持 *.vue 后缀的文件,所以在 vue 项目中引入的时候需要创建一个shims-vue.d.ts 文件,放在项目项目对应使用目录下,例如 src/shims-vue.d.ts,用来支持*.vue 后缀的文件;

2.tslint配置 “rules”: {…}

// 关闭console
"no-console": [true, "log", "dir", "table"]

// tslint的函数前后空格:
"space-before-function-paren": ["error", {
"anonymous": "always",
"named": "always",
"asyncArrow": "always"
}]


// tslint分号的配置:
"semicolon": [true, "never"]


TSlint其他配置

3.路由改造(全局路由拦截,用户登陆验证等),修改App.vue文件,如下

// App.vue 文件
import router from '@/router/index'

router.beforeEach((to: any, from: any, next: any) => {
if (to.name === 'login') {
next({name: 'home/index'})
} else {
next()
}
})

例如:


4. *.vue文件改造

注:template 和 style 跟以前的写法保持一致,只有 script 的变化


5.父组件传值给子组件(使用vue-property-decorator装饰器 @Prop)

6.子组件传值给父组件(使用vue-property-decorator装饰器 @Emit)

注:@Emit其他写法


7.侦听器watch(使用vue-property-decorator装饰器 @Watch)

注:handler,immediate和deep

如下写的函数其实就是在写这个handler方法里面的;

watch: {
firstName (val) {
this.fullName = val + ' ' + this.lastName
}
}



当值第一次绑定的时候,不会执行监听函数,只有值发生改变才会执行。如果我们需要在最初绑定值的时候也执行函数,则就需要用到immediate属性为true。

当需要监听一个对象的改变时,普通的watch方法无法监听到对象内部属性的改变,只有data中的数据才能够监听到变化,此时就需要deep属性对对象进行深度监听。
————————————————
版权声明:本文为CSDN博主「非为000」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/qq_30669833/article/details/90487700

原文地址:https://www.cnblogs.com/ygunoil/p/12133643.html