introductionIn recent years, the call for TypeScript has become increasingly louder, and Typescript has become a necessary skill for the front-end. TypeScript is a superset of JS types and supports features such as generics, types, namespaces, enumerations, etc., making up for the shortcomings of JS in large-scale application development. When learning TypeScript alone, you will feel that many concepts are relatively easy to understand, but there are still many pitfalls when using it in combination with some frameworks. For example, when using frameworks such as React and Vue, combining them with TypeScript will become a major obstacle. You need to check the definitions of some complex types in the .d.ts declaration files provided by the framework, and the writing methods of components, etc., and you need to make significant adjustments. This article mainly combines my experience to talk with you about how to smoothly transition from BuildInstall through the official scaffolding # 1. If Vue CLI is not installed, install it first npm install --global @vue/cli The latest Just run The command line will then ask you to select a preset. Use the arrow keys to select Manually select features. Next, just make sure the TypeScript and Babel options are selected, as shown below: Then configure the rest of the settings as shown below: Once the setup is complete, vue cli will start installing dependencies and setting up the project. Directory resolutionAfter the installation is complete, open the project and you will find that the project directory structure after integrating ts is like this: |-- ts-vue |-- .browserslistrc # browserslistrc configuration file (used to support Autoprefixer) |-- .eslintrc.js # eslint configuration |-- .gitignore |-- babel.config.js # babel-loader configuration |-- package-lock.json |-- package.json # package.json dependencies|-- postcss.config.js # postcss configuration|-- README.md |-- tsconfig.json # typescript configuration |-- vue.config.js # vue-cli configuration |-- public # static resources (will be copied directly) | |-- favicon.ico # favicon icon| |-- index.html # html template|-- src | |-- App.vue # Entry page| |-- main.ts # Entry file loading component initialization, etc.| |-- shims-tsx.d.ts | |-- shims-vue.d.ts | |-- assets # Theme fonts and other static resources (loaded by webpack) | |-- components # Global components| |-- router # Routing| |-- store # Global vuex store | |-- styles # Global styles| |-- views # All pages|-- tests # Tests In fact, roughly speaking, there is not much difference from the project directory built with
useBefore we start, let's take a look at some very useful libraries for using typescript in vue import { Vue, Component, Inject, Provide, Prop, Model, Watch, Emit, Mixins } from 'vue-property-decorator' import { Module, VuexModule, Mutation, Action, MutationAction, getModule } from 'vuex-module-decorators' Component DeclarationThe way to create a component becomes as follows import { Component, Prop, Vue, Watch } from 'vue-property-decorator'; @Component export default class Test extends Vue { } data object import { Component, Prop, Vue, Watch } from 'vue-property-decorator'; @Component export default class Test extends Vue { private name: string; } Prop Declaration @Prop({ default: false }) private isCollapse!: boolean; @Prop({ default: true }) private isFirstLevel!: boolean; @Prop({ default: "" }) private basePath!: string; !: means it must exist, ?: means it may not exist. These two are grammatically called assignment assertions @Prop(options: (PropOptions | Constructor[] | Constructor) = {})
method In js, the method needs to be declared in the method object, which now becomes as follows public clickFunc(): void { console.log(this.name) console.log(this.msg) } Watch monitoring properties @Watch("$route", { immediate: true }) private onRouteChange(route: Route) { const query = route.query as Dictionary<string>; if (query) { this.redirect = query.redirect; this.otherQuery = this.getOtherQuery(query); } } @Watch(path: string, options: WatchOptions = {}) options contains two properties: immediate?:boolean: whether to call the callback function immediately after the listening starts / deep?:boolean: whether to call the callback function when the property of the monitored object is changed @Watch('arr', { immediate: true, deep: true }) computed public get allname() { return 'computed ' + this.name; } allname is the calculated value, name is the monitored value Lifecycle Functions public created(): void { console.log('created'); } public mounted():void{ console.log('mounted') } emit events import { Vue, Component, Emit } from 'vue-property-decorator' @Component export default class MyComponent extends Vue { count = 0 @Emit() addToCount(n: number) { this.count += n } @Emit('reset') resetCount() { this.count = 0 } @Emit() returnValue() { return 10 } @Emit() onInputChange(e) { return e.target.value } @Emit() promise() { return new Promise(resolve => { setTimeout(() => { resolve(20) }, 0) }) } } Use js writing export default { data() { return { count: 0 } }, methods: { addToCount(n) { this.count += n this.$emit('add-to-count', n) }, resetCount() { this.count = 0 this.$emit('reset') }, returnValue() { this.$emit('return-value', 10) }, onInputChange(e) { this.$emit('on-input-change', e.target.value, e) }, promise() { const promise = new Promise(resolve => { setTimeout(() => { resolve(20) }, 0) }) promise.then(value => { this.$emit('promise', value) }) } } }
vuex Before using the store decorator, let's go over the traditional store usage. export default { namespaced:true, state:{ foo:"" }, getters:{ getFoo(state) { return state.foo} }, mutations: setFooSync(state, payload){ state.foo = payload } }, actions:{ setFoo({commit},payload){ commot("getFoo",payload) } } } Then start using import { VuexModule, Mutation, Action, getModule, Module } from "vuex-module-decorators"; export default class TestModule extends VuexModule { } VuexModule provides some basic properties, including namespaced, state, getters, modules, mutations, actions, context @Module({ dynamic: true, store, name: "settings" }) class Settings extends VuexModule implements ISettingsState { } The module itself has several configurable properties:
@Mutation private SET_NAME(name: string) { // Set the username this.name = name; } @Action public async Login(userInfo: { username: string; password: string }) { // Login interface and get token let { username, password } = userInfo; username = username.trim(); const { data } = await login({ username, password }); setToken(data.accessToken); this.SET_TOKEN(data.accessToken); } export const UserModule = getModule(User); This is the end of this article about how to use TypeScript in Vue. For more information about how to use TypeScript in Vue, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope you will support 123WORDPRESS.COM in the future! You may also be interested in:
|
<<: MySQL 8.X installation tutorial under Windows
>>: How to parse the attribute interface of adding file system in Linux or Android
CSS Position The position attribute specifies the...
The WeChat mini-program native components camera,...
1. Install Apache $ sudo apt update && su...
Detailed explanation of mysql count The count fun...
MySQL consistency log What happens to uncommitted...
SQL method for calculating timestamp difference O...
1. DNS server concept Communication on the Intern...
This article mainly summarizes some commonly used...
Loading kernel symbols using gdb arm-eabi-gdb out...
On some websites, you can often see some pictures...
1. Install MySQL database ① Download and unzip an...
Today, when I was configuring Tomcat to access th...
Open DREAMWEAVER and create a new HTML. . Propert...
Suppose there is a table: reward (reward table), ...
In more and more websites, the use of XHTML is rep...