Vue-cli4 + TypeScript3.0开发项目
1、安装vue-cli4
npm install -g @vue/cli
安装完成之后可以通过vue -V检查版本
2、创建项目
vue create 项目名称
需要ts,选择自主安装,通过上/下键和空格键选择要用到的插件,选好后回车即可
安装后的目录如下
其中,tsconfig.json是ts项目的配置文件
shims-vue.d.ts文件用来对vue进行声明,使ts能够识别.vue后缀的文件。
3、启动项目
npm run serve
4、ts语法使用
ts语法
vue-class-component是官方提供的使用类的方式编写组件
vue-property-decorator(详细说明)则完全依赖于vue-class-component,它将一些常用的钩子都封装成了装饰器
<script lang="ts">
import { Vue, Component } from 'vue-property-decorator';
import HelloWorld from '@/components/HelloWorld.vue'
@Component({
//装饰器内部可以放props,components等
components: {
HelloWorld
}
})
export default class Home extends Vue {
/**
*date数据
*/
//布尔
isShow = false;
//数字
num = 123;
//字符串
msg = "最近好吗?要好好照顾自己哦";
//数组,两种写法
list: Array<string> = ['a', 'b', 'c'];
list1: number[] = [1, 2, 3];
//元组
tuple: [string,number] = ["hello", 10];
//任何类型any,不期待,存在警告
//notSure: any = 4;
/**
*生命周期
*/
mounted(){
this.greet();
this.getData({a: "aaa",b: 2});
this.bindEvents();
}
/**
*computed计算属性
*/
get computedMsg(){
return "雯," + this.msg;
}
/**
*操作dom
*/
bindEvents(){
//需要声明类型,否则会报类型错误
const drag: any = this.$refs.drag
drag.addEventListener('click', (e: any) => {
drag.style.borderColor = 'red'
})
}
/**
*methods方法
*/
greet(): void {
console.log(111111)
}
//函数声明`
getData({a,b}: {a: string;b: number}): void{
console.log(a,b);
}
}
</script>
typescript难点梳理
vue使用typescript的坑
https://www.jianshu.com/p/286ceb8e866b
使用window全局变量
在src根目录*.d.ts文件中进行类型申明
interface Window {
a: any;
}
5、检查报错
报错1:
eslint格式检查引起的,可以在.eslintrc.js的rules中添加如下配置
rules: {
'no-parsing-error': 'off',
"generator-star-spacing": "off",
"no-tabs":"off",
"no-unused-vars":"off",
"no-irregular-whitespace":"off",
'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off',
'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off'
}
报错2:
写入下面的代码,tslint觉得自己根据右边的false判断出isShow的类型是boolean,所以,认为此处是多此一举。
isShow: boolean = false;
解决办法:
在.eslintrc.js的rules中添加如下配置
"no-inferrable-types": [true, "ignore-params", "ignore-properties"],
ignore-params允许为函数参数指定不可推出的类型注释。
ignore-properties 允许为类属性指定不可推出的类型注释。
.eslintrc.js中rules的配置项说明(来源:http://blog.csdn.net/zw52yany/article/details/78688837)
rules: 规则
{
//ts专用
adjacent-overload-signatures : true, // Enforces function overloads to be consecutive.
ban-comma-operator:true, //禁止逗号运算符。
ban-type: [true, ["object","User {} instead."],["string"]] //禁止类型
member-access: [true , "no-public"||"check-accessor"|| "check-constructor" || "check-parameter-property" ] , //类成员必须声明 private public ....
member-order: [true, {order:....}], //类声明排序
no-any: true,//不需使用any类型
no-empty-interface:true //禁止空接口 {}
no-import-side-effect: [true, {"ignore-module": "(\\.html|\\.css)$"}], //禁止导入带有副作用的语句
no-inferrable-types:[true, "ignore-params", "ignore-properties"], //不允许将变量或参数初始化为数字,字符串或布尔值的显式类型声明。
no-internal-module:true, //不允许内部模块
no-magic-numbers: [true,1,2,3], //不允许在变量赋值之外使用常量数值。当没有指定允许值列表时,默认允许-1,0和1
no-namespace: [ true,"allpw-declarations"], //不允许使用内部modules和命名空间
no-non-null-assertion: true , //不允许使用!后缀操作符的非空断言。
no-parameter-reassignment: true, //不允许重新分配参数
no-reference: true, // 禁止使用/// <reference path=> 导入 ,使用import代替
no-unnecessary-type-assertion: true, //如果类型断言没有改变表达式的类型就发出警告
no-var-requires: true, //不允许使用var module = require("module"),用 import foo = require('foo')导入
only-arrow-functions:[true,"allow-declarations","allow-named-functions"], //允许箭头表达式,不需要传统表达式 ; 允许独立的函数声明 ;允许表达,function foo() {}但不是function() {}
prefer-for-of:true, //建议使用for(..of)
promise-function-async: true, 要求异步函数返回promise
typedef: [true, "call-signature", "parameter", "member-variable-declaration"], //需要定义的类型存在
typedef-whitespace: true, //类型声明的冒号之前是否需要空格
unified-signatures: true, //重载可以被统一联合成一个
//function 专用
await-promise: true, //警告不是一个promise的await
ban: [
true,
"eval",
{"name": "$", "message": "please don't"},
["describe", "only"],
{"name": ["it", "only"], "message": "don't focus tests"},
{
"name": ["chai", "assert", "equal"],
"message": "Use 'strictEqual' instead."
},
{"name": ["*", "forEach"], "message": "Use a regular for loop instead."}
],
curly: true, //for if do while 要有括号
forin:true, //用for in 必须用if进行过滤
import-blacklist:true, //允许使用import require导入具体的模块
label-postion: true, //允许在do/for/while/swith中使用label
no-arg:true, //不允许使用 argument.callee
no-bitwise:true, //不允许使用按位运算符
no-conditional-assignmen: true, //不允许在do-while/for/if/while判断语句中使用赋值语句
no-console:true, //不能使用console
no-construct: true, //不允许使用 String/Number/Boolean的构造函数
no-debugger: true, //不允许使用debugger
no-duplicate-super: true, //构造函数两次用super会发出警告
no-empty:true, //不允许空的块
no-eval: true, //不允许使用eval
no-floating-promises: true, //必须正确处理promise的返回函数
no-for-in-array: true, //不允许使用for in 遍历数组
no-implicit-dependencies: true, //不允许在项目的package.json中导入未列为依赖项的模块
no-inferred-empty-object-type: true, //不允许在函数和构造函数中使用{}的类型推断
no-invalid-template-strings: true, //警告在非模板字符中使用${
no-invalid-this:true, //不允许在非class中使用 this关键字
no-misused-new: true, //禁止定义构造函数或new class
no-null-keyword: true, //不允许使用null关键字
no-object-literal-type-assertion:true, //禁止objext出现在类型断言表达式中
no-return-await:true, //不允许return await
arrow-parens: true, //箭头函数定义的参数需要括号
}