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?
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 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.
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 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,'ig') if(!checkReg.test(checker[i])) { console.error(checked[i] + 'is not a ' + 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 'query-string';
然而当你打印querystring 的时候是undefined。如何解决呢?小编的方法也仅供参考
新建module.js文件
import querystring from 'query-string'; export const qs = querystring;
utile.ts 文件
import { qs } from './module.js';
解决了。打印qs不再是undefined,可以正常使用qs库了哦。
至此本文就将ts在vue中的配置介绍结束,此文只代表个人看法,考虑到项目的扩展性,所以没有全部替换成ts,只是尝试性在vue中引入ts,还有很多需要改进的地方,如果有更好的建议和意见可以联系我!
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
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!

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version
SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.