Home  >  Article  >  Web Front-end  >  How to use ts in vue (detailed tutorial)

How to use ts in vue (detailed tutorial)

亚连
亚连Original
2018-06-02 17:29:328222browse

This article mainly introduces the sample code of how to use ts in vue. Now I will share it with you and give you a reference.

This article introduces the sample code of how to use ts in vue and shares it with everyone. The details are as follows:

Note: This article does not change all vue to ts, but can Implanting ts files in the original project is currently only a practical stage and a transition to the ts conversion process.

What is the use of ts?

Type checking, direct compilation to native js, introduction of new syntax sugar

Why use ts?

The design purpose of TypeScript should be to solve the "pain points" of JavaScript: weak types and no namespace, making it difficult to modularize and not suitable for developing large programs. In addition, it also provides some syntactic sugar to help everyone practice object-oriented programming more conveniently.

Typescript can not only constrain our coding habits, but also serve as annotations. When we see a function, we can immediately know how to use it, what value needs to be passed, and what type the return value is. It is clear at a glance, which greatly improves the maintainability of large projects. It won't cause developers to shoot themselves in the foot.

Angular: Why did we choose TypeScript?

  1. Excellent tools in TypeScript

  2. TypeScript is a superset of JavaScript

  3. TypeScript makes abstractions visible

  4. TypeScript makes code easier to read and understand

Yes, I know this doesn't seem intuitive. Let me illustrate what I mean with an example. Let's take a look at this function jQuery.ajax(). What information can we get from its signature?

#The only thing we know for sure is that this function takes two parameters. We can guess at these types. Maybe the first is a string and the second is a configuration object. But this is just speculation and we could be wrong. We don't know what options go into the settings object (their names and types), or what the function returns.

It is impossible to call this function without checking the source code or documentation. Examining the source code is not an option - the purpose of having functions and classes is to use them without knowing how to implement them. In other words, we should rely on their interfaces, not their implementations. We could check the documentation, but it's not the best development experience - it takes extra time, and the documentation is often out of date.

So, although it is easy to read jQuery.ajax(url,settings), to really understand how to call this function, we need to read its implementation or its documentation.

The following is a type version:

It gives us more information.

  1. The first parameter of this function is a string.

  2. Setting parameters is optional. We can see all the options that can be passed into the function, not only their names, but also their types.

  3. The function returns a JQueryXHR object, and we can see its properties and functions.

Typed signatures are definitely longer than untyped signatures, but :string, :JQueryAjaxSettings and JQueryXHR are not cluttered. They are important documents that improve the understandability of your code. We can understand the code more deeply without having to dive into the implementation or read the documentation. My personal experience is that I can read typed code faster because the types provide more context to understand the code.

Excerpted from Angular: Why do we choose TypeScript?

ts Is it easy to learn?

One of the design highlights of TypeScript is that it does not abandon the syntax of JavaScript and start a new one, but instead makes it a superset of JavaScript (this credit should be credited to Anders), so that any legal JavaScript statement It is legal under TypeScript, which means that the learning cost is very low. If you have a relatively in-depth understanding of JavaScript, you can actually get started with TypeScript quickly, because its design is based on JavaScript usage habits and conventions.
Some simple examples, easy to understand at a glance:

Basic type

let isDone: boolean = false; // 布尔值
let decLiteral: number = 6;  // 数字
let name: string = "bob"; // 字符串
let list: number[] = [1, 2, 3]; // 数组
...
...

Interface

function printLabel(labelledObj: { label: string }) {  console.log(labelledObj.label);
 } let myObj = { size: 10, label: "Size 10 Object" };
 printLabel(myObj);

The type checker will check the call to printLabel. printLabel has one parameter, and requires that this object parameter has an attribute named label of type string. It should be noted that the object parameter we pass in will actually contain many properties, but the compiler will only check whether those required properties exist and whether their types match.

Of course there are some advanced usages, I won’t go into too much introduction here, learn more

How to apply ts in vue project?

1. First install ts

npm install --save-dev typescript npm install --save-dev ts-loader

2. Create the tsconfig.json file in the root directory

{
  "compilerOptions": {
   "experimentalDecorators": true,
   "emitDecoratorMetadata": true,
   "lib": ["dom","es2016"],
   "target": "es5"
  },
  "include": ["./src/**/*"] }

3. Add ts-loader

in the configuration
{
  test: /\.tsx?$/,
  loader: 'ts-loader',  exclude: /node_modules/,   options: {
   appendTsSuffixTo: [/\.vue$/],
  }
 }

4. Finally, add the .ts suffix and it will be OK. Under the webpack.base.conf.js file

现在就可以在我们原本的项目中使用ts文件了。

如何实践?

1、如何在js中引用ts文件?

由于js文件没有类型检测,当我们把ts文件引入的时候,ts文件会转化成js文件,所以在js文件中引用ts文件的方法类型检测机制不会生效。也就是说只有在ts文件内才会有类型检测机制。

那么怎么在js文件中使用类型检测机制呢?小编自己封装了一套typeCheck的decorator方法,仅供参考!用法如下:

@typeCheck('object','number') deleteItem(item,index) {}

检测deleteItem方法参数: item为object类型,index为number类型,如果类型不匹配将会抛出异常

部分代码献上:

const _check = function (checked,checker) {
    check:      for(let i = 0; i < checked.length; i++) {       if(/(any)/ig.test(checker[i]))          continue check;       if(_isPlainObject(checked[i]) && /(object)/ig.test(checker[i]))      continue check;       if(_isRegExp(checked[i]) && /(regexp)/ig.test(checker[i]))      continue check;       if(Array.isArray(checked[i]) && /(array)/ig.test(checker[i]))      continue check;       let type = typeof checked[i];       let checkReg = new RegExp(type,&#39;ig&#39;)       if(!checkReg.test(checker[i])) {          console.error(checked[i] + &#39;is not a &#39; + checker[i]);          return false;
   }
  }  return true;
 } /**
  * @description 检测类型
  *  1.用于校检函数参数的类型,如果类型错误,会打印错误并不再执行该函数;
  *  2.类型检测忽略大小写,如string和String都可以识别为字符串类型;
  *  3.增加any类型,表示任何类型均可检测通过;
  *  4.可检测多个类型,如 "number array",两者均可检测通过。正则检测忽略连接符 ;
  */
 export function typeCheck() {     const checker = Array.prototype.slice.apply(arguments);       return function (target, funcName, descriptor) {          let oriFunc = descriptor.value;
       descriptor.value = function () {           let checked = Array.prototype.slice.apply(arguments);             let result = undefined;             if(_check(checked,checker) ){
           result = oriFunc.call(this,...arguments);
    }       return result;
   }
  }
 };

ts的类型检测配合typeCheck基本上已经满足了我们的需要。

2、如何在ts中引用js文件?

由于js文件中没有类型检测,所以ts文件引入js文件时会转化为any类型,当然我们也可以在 .d.ts文件中声明类型。

如 global.d.ts 文件

当然有的时候我们需要使用一些库,然而并没有声明文件,那么我们在ts文件中引用的时候就会是undefined。这个时候我们应该怎么做?

比如我想要在util.ts文件中用 ‘query-string'的时候我们就会这样引用:

import querystring from &#39;query-string&#39;;

然而当你打印querystring 的时候是undefined。如何解决呢?小编的方法也仅供参考

新建module.js文件

import querystring from &#39;query-string&#39;; export const qs = querystring;

utile.ts 文件

import { qs } from &#39;./module.js&#39;;

解决了。打印qs不再是undefined,可以正常使用qs库了哦。

至此本文就将ts在vue中的配置介绍结束,此文只代表个人看法,考虑到项目的扩展性,所以没有全部替换成ts,只是尝试性在vue中引入ts,还有很多需要改进的地方,如果有更好的建议和意见可以联系我!

上面是我整理给大家的,希望今后会对大家有帮助。

相关文章:

JS实现将链接生成二维码并转为图片的方法

基于vue1和vue2获取dom元素的方法

nodejs+mongodb aggregate级联查询操作示例

The above is the detailed content of How to use ts in vue (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn