Home Web Front-end JS Tutorial How to use TypeScript methods in Vue components (detailed tutorial)

How to use TypeScript methods in Vue components (detailed tutorial)

Jun 02, 2018 pm 05:14 PM
typescript use method

Typescript can not only constrain our coding habits, but also serve as comments. When we see a function, we can immediately know how to use it. This article mainly introduces the method of using TypeScript in Vue components. Friends who need it can refer to

Note: This article does not replace all vue with ts, but can be used in the original project. Implanting ts files is currently only a practical stage, 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?

  • Excellent tools in TypeScript

  • TypeScript is a superset of JavaScript

  • TypeScript makes abstractions visible

  • 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 has 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.

  • The first parameter of this function is a string.

  • 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.

  • 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 statements are all legal under TypeScript, which means that the learning cost is very low. If you have a deeper understanding of JavaScript, you can actually get started with TypeScript quickly, because its design is based on JavaScript usage habits and Convention.

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 look at 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、首先安装ts

npm install --save-dev typescript npm install --save-dev ts-loader
Copy after login

2、在根目录建tsconfig.json文件

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

3、在配置中添加 ts-loader

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

4、最后把 .ts 后缀添加上就OK了,在webpack.base.conf.js文件下


现在就可以在我们原本的项目中使用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&#39;的时候我们就会这样引用:

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 TypeScript methods in Vue components (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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. How to write a novel in the Tomato Free Novel app. Share the tutorial on how to write a novel in Tomato Novel. Mar 28, 2024 pm 12:50 PM

Tomato Novel is a very popular novel reading software. We often have new novels and comics to read in Tomato Novel. Every novel and comic is very interesting. Many friends also want to write novels. Earn pocket money and edit the content of the novel you want to write into text. So how do we write the novel in it? My friends don’t know, so let’s go to this site together. Let’s take some time to look at an introduction to how to write a novel. Share the Tomato novel tutorial on how to write a novel. 1. First open the Tomato free novel app on your mobile phone and click on Personal Center - Writer Center. 2. Jump to the Tomato Writer Assistant page - click on Create a new book at the end of the novel.

How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) How to recover deleted contacts on WeChat (simple tutorial tells you how to recover deleted contacts) May 01, 2024 pm 12:01 PM

Unfortunately, people often delete certain contacts accidentally for some reasons. WeChat is a widely used social software. To help users solve this problem, this article will introduce how to retrieve deleted contacts in a simple way. 1. Understand the WeChat contact deletion mechanism. This provides us with the possibility to retrieve deleted contacts. The contact deletion mechanism in WeChat removes them from the address book, but does not delete them completely. 2. Use WeChat’s built-in “Contact Book Recovery” function. WeChat provides “Contact Book Recovery” to save time and energy. Users can quickly retrieve previously deleted contacts through this function. 3. Enter the WeChat settings page and click the lower right corner, open the WeChat application "Me" and click the settings icon in the upper right corner to enter the settings page.

How to set font size on mobile phone (easily adjust font size on mobile phone) How to set font size on mobile phone (easily adjust font size on mobile phone) May 07, 2024 pm 03:34 PM

Setting font size has become an important personalization requirement as mobile phones become an important tool in people's daily lives. In order to meet the needs of different users, this article will introduce how to improve the mobile phone use experience and adjust the font size of the mobile phone through simple operations. Why do you need to adjust the font size of your mobile phone - Adjusting the font size can make the text clearer and easier to read - Suitable for the reading needs of users of different ages - Convenient for users with poor vision to use the font size setting function of the mobile phone system - How to enter the system settings interface - In Find and enter the "Display" option in the settings interface - find the "Font Size" option and adjust it. Adjust the font size with a third-party application - download and install an application that supports font size adjustment - open the application and enter the relevant settings interface - according to the individual

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

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.

The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) The secret of hatching mobile dragon eggs is revealed (step by step to teach you how to successfully hatch mobile dragon eggs) May 04, 2024 pm 06:01 PM

Mobile games have become an integral part of people's lives with the development of technology. It has attracted the attention of many players with its cute dragon egg image and interesting hatching process, and one of the games that has attracted much attention is the mobile version of Dragon Egg. To help players better cultivate and grow their own dragons in the game, this article will introduce to you how to hatch dragon eggs in the mobile version. 1. Choose the appropriate type of dragon egg. Players need to carefully choose the type of dragon egg that they like and suit themselves, based on the different types of dragon egg attributes and abilities provided in the game. 2. Upgrade the level of the incubation machine. Players need to improve the level of the incubation machine by completing tasks and collecting props. The level of the incubation machine determines the hatching speed and hatching success rate. 3. Collect the resources required for hatching. Players need to be in the game

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

Quickly master: How to open two WeChat accounts on Huawei mobile phones revealed! Quickly master: How to open two WeChat accounts on Huawei mobile phones revealed! Mar 23, 2024 am 10:42 AM

In today's society, mobile phones have become an indispensable part of our lives. As an important tool for our daily communication, work, and life, WeChat is often used. However, it may be necessary to separate two WeChat accounts when handling different transactions, which requires the mobile phone to support logging in to two WeChat accounts at the same time. As a well-known domestic brand, Huawei mobile phones are used by many people. So what is the method to open two WeChat accounts on Huawei mobile phones? Let’s reveal the secret of this method. First of all, you need to use two WeChat accounts at the same time on your Huawei mobile phone. The easiest way is to

See all articles