Home Web Front-end JS Tutorial How to use ts in vue (detailed tutorial)

How to use ts in vue (detailed tutorial)

Jun 02, 2018 pm 05:29 PM
use Tutorial detailed

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]; // 数组
...
...
Copy after login

Interface

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

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
Copy after login

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

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

3. Add ts-loader

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

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) {}
Copy after login

检测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;
   }
  }
 };
Copy after login

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;;
Copy after login

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

新建module.js文件

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

utile.ts 文件

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

解决了。打印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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Tutorial on how to use Dewu Tutorial on how to use Dewu Mar 21, 2024 pm 01:40 PM

Dewu APP is currently a very popular brand shopping software, but most users do not know how to use the functions in Dewu APP. The most detailed usage tutorial guide is compiled below. Next is the Dewuduo that the editor brings to users. A summary of function usage tutorials. Interested users can come and take a look! Tutorial on how to use Dewu [2024-03-20] How to use Dewu installment purchase [2024-03-20] How to obtain Dewu coupons [2024-03-20] How to find Dewu manual customer service [2024-03-20] How to check the pickup code of Dewu [2024-03-20] Where to find Dewu purchase [2024-03-20] How to open Dewu VIP [2024-03-20] How to apply for return or exchange of Dewu

What software is crystaldiskmark? -How to use crystaldiskmark? What software is crystaldiskmark? -How to use crystaldiskmark? Mar 18, 2024 pm 02:58 PM

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

How to download foobar2000? -How to use foobar2000 How to download foobar2000? -How to use foobar2000 Mar 18, 2024 am 10:58 AM

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

How to use Baidu Netdisk app How to use Baidu Netdisk app Mar 27, 2024 pm 06:46 PM

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

How to use NetEase Mailbox Master How to use NetEase Mailbox Master Mar 27, 2024 pm 05:32 PM

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? BTCC tutorial: How to bind and use MetaMask wallet on BTCC exchange? Apr 26, 2024 am 09:40 AM

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

In summer, you must try shooting a rainbow In summer, you must try shooting a rainbow Jul 21, 2024 pm 05:16 PM

After rain in summer, you can often see a beautiful and magical special weather scene - rainbow. This is also a rare scene that can be encountered in photography, and it is very photogenic. There are several conditions for a rainbow to appear: first, there are enough water droplets in the air, and second, the sun shines at a low angle. Therefore, it is easiest to see a rainbow in the afternoon after the rain has cleared up. However, the formation of a rainbow is greatly affected by weather, light and other conditions, so it generally only lasts for a short period of time, and the best viewing and shooting time is even shorter. So when you encounter a rainbow, how can you properly record it and photograph it with quality? 1. Look for rainbows. In addition to the conditions mentioned above, rainbows usually appear in the direction of sunlight, that is, if the sun shines from west to east, rainbows are more likely to appear in the east.

What software is photoshopcs5? -photoshopcs5 usage tutorial What software is photoshopcs5? -photoshopcs5 usage tutorial Mar 19, 2024 am 09:04 AM

PhotoshopCS is the abbreviation of Photoshop Creative Suite. It is a software produced by Adobe and is widely used in graphic design and image processing. As a novice learning PS, let me explain to you today what software photoshopcs5 is and how to use photoshopcs5. 1. What software is photoshop cs5? Adobe Photoshop CS5 Extended is ideal for professionals in film, video and multimedia fields, graphic and web designers who use 3D and animation, and professionals in engineering and scientific fields. Render a 3D image and merge it into a 2D composite image. Edit videos easily

See all articles