TypeScript is used in Vue3
Vue3: The syntax is unchanged and TS support is good. I’ve already covered Vue3 before. If you haven’t seen it, check it out
Understand the TypeScript
TypeScript
(TS), yesJavaScript
Superset of JS (TS has JS, TS also has JS)TypeScript = type + JavaScript
(Added a type system to JS)
//TS has a clear type distinction
let name: string = "Zhang";
//JS has no type distinction
let name = "Zhang"
Copy the code
TypeScript
Derived from useJavaScript
Large projects developed. Due to the limitations of the JavaScript language itself,Difficult to manage and maintain large project development. So Microsoft developed TypeScript to make it suitable for large projects.
TypeScript
advantage
JS has a “congenital defect “, most of the errors are type errors (Uncaught TypeError)
Typed way of thinking
, make the development more rigorous, find mistakes in advance.- The type system improves code readability,
Easy to maintain and refactor code
. - added
interface
.The enumeration
JS missing functions - The Vue3 source code uses TS. Angular supports TS by default. React works perfectly with TS
TypeScript
The rules
In TS, in order to make the code more standard, easy to maintain, add the type check, provide a number of type check, Boolean (Number), string (string), array (array), tuple (tuple), enumeration (enum), Any type (any), null and undefined, void, never
The general usage is as follows.
// Boolean type (Boolean)
let flag:boolean=false;
flag=true
// Number type (number)
let num:number=123
// String type (string)
let str:string="Good fellow"
// Array type (array)
// The first way to define an array
let arr:number[]=[1.2.3]
let arr:string[]=['Joe'.'bill'.'Cathy']
// Define an associative type array, same as above
let arr:(number | string)[]
// If you are not sure whether you are defining a number or a string or a Boolean type, you can use any (I would like to call it YYds!!).
let arr:any[]=['Joe'.15.'bill'.18, {name:'bill'.age:20}]
// The second way to define arrays (using generics)
let arr2:Array<string> = ["Zhang"."Bill"]
// If you want to write objects in an array, and restrict the content format
const arr:{name:string,age:number}[]=[
{name:'Joe'.age:18},
{name:'bill'.age:20}]// If the format is used in many places, the type alias type can be used
type Lady={name:string,age:number}
const arr:Lady[]=[
{name:'Joe'.age:18},
{name:'bill'.age:20}]// You can also use the class method
class Lady {name:string,age:number}
const arr:Lady[]=[
{name:'Joe'.age:18};
{name:'bill'.age:20}]// A tuple is a type of array. You can specify the type of the value in the array
// The type, position, and number of the assignment must be the same as the type, position, and number of the definition. There's no need. I haven't used it.
let arr:[number,string]=[123."Zhang"]
// Enumeration types (enum) are primarily used to define identifiers
// By default, One starts at 0 and the remaining members grow automatically from 1.Enum Status {One, Two, Three} Can define the initial value, or assign the value to enum Status {One=1,
Two,
Three
}
// Any type (any)
// Any type can be classified as any. This makes any the top-level type of the type system (also known as the global super type).
// If you really don't know what type it is, write any, but don't write any all the way through
let a:any=120
a='123'
/ / void type
// Indicates that there is no type. It is used to define methods that do not return values
function fn() :void{
console.log(123)}// If there is a return value, write what is returned
function fn() :number{
return 123
}
/ / never type
// The never type represents the types of values that never exist.
// The 'never' type, like null and undefined, is a subtype of any type and can be assigned to any type.
// But no type is a subtype of never or can be assigned to never (except never itself), and even any cannot be assigned to never
Copy the code
If you define what the type is, then you assign it to the corresponding type, and if you assign it to something other than the corresponding type, then you get an error, okay Interface: What is an interface? An interface is also a type used to constrain users. Its function is to further define the properties of an object.
Other supplementary
- Interface: An interface is a specification definition that defines a specification of behavior and actions
// Interface, such as defining something that has been used many times, can be used in interface,? Yes: not sure if this parameter exists (optional)
interface Man {
name:string; age:number; job ? :string; }const man={name:'bill'.age:20}
const fn=(man:Man) = >{
if(man.name){
console.log(man.name)
}else if(man.age){
console.log(man.age)
}else if(man.job){
console.log(man.job)
}
}
// If you still want to write arbitrary things, then
interface Man {
[propname:string]:any
}
// You can also define methods. Here we define a string return value
interface Man {
say():string
}
// Can also be upgraded
// In this case Mans must follow Man's rules and can add defined things
interface Mans extends Man{
fullname:string
}
Copy the code
- Generics: You can use generics to create reusable components that can support multiple types of data. This allows users to use components with their own data types. Generics help us avoid duplicate code and support for non-specific data types (type validation)
So let’s say we write a function, and we pass in arguments, and we ask to return arguments, and in that case, we write ts
function get1(val:string) :string{
return val
}
function get2(val:number) :number{
return val
}
// This is cumbersome, but we can use any
function get3(val:any) :any{
return val
}
Any, however, is equivalent to abandoning type testing, whereas generics support non-specific data types
function get4<T> (val:T) :T{
return val
}
// You can use any capital letter, but it must be the same.
get4<number>(123)// Write corresponding words
Copy the code
Ok, that’s basically it. In fact, you can write projects in this way. If you want to learn more about TypeScript, you can check out other major TypeScript tutorials
- Get started with typescript 2021
- A good TypeScript summary
- 1.2 W word | great TypeScript introductory tutorial
Used in vue3TypeScript
Let’s go straight to VUE3.
First we need to create a vue3+TypeScript project, create it ourselves, open the file, then go to the app. vue file, and you’ll see that it automatically introduces defineComponent, so there’s a question about what defineComponent is, DefineComponent itself is pretty simple, but its main function is to push to TypeScript types. For a TS file, if we write export default {} directly, at this time, to the editor, {} is only an Object type, there is no specific prompt for us to vue component {} should have attributes. But if you add a layer of defineComponet, export default defineComponent({}), then {} becomes the parameter of defineComponent, so the hint of parameter type can realize the hint of attribute in {}. In addition, some types of parameters can be derived and other operations.
As we discussed last time, we used this when we defined reactive data in VUe3reactive
andref
, so let’s define it in terms of interfacesreactive
(We’ve talked about interfaces.)
// The first way
<script lang="ts">
import { defineComponent, reactive } from 'vue';
interface User{
name:string,
age:number,
say(username:string):void
}
export default defineComponent({
name: 'Home'.setup(){
let fullname:User=reactive({
name:'Joe'.age:20.say(username:string){
console.log(username)
}
})
return{}}}); </script>Copy the code
So let’s write it a different way, so we go to Reactive and CTRL + left mouse to go into the source code,
As you can see, it uses generics, and we said generics before, so we can use generics to constrain our code
<script lang="ts">
import { defineComponent, reactive } from 'vue';
interface User{
name:string,
age:number,
say(username:string):void
}
export default defineComponent({
name: 'Home'.setup(){
// The second way
let fullname=reactive<User>({
name:'Joe'.age:20.say(username:string){
console.log(username)
}
})
// The third way
let fullname=reactive({
name:'Joe'.age:20.say(username:string){
console.log(username)
}
})as User
return{}}}); </script>Copy the code
So go to the ref source, you can also use the generic way
let num=ref<number|string>('999')
let nums:string=ref('999')// Can not be allocated
Copy the code
Function using return value (same as before)
function fn() :string{
return '1562'
}
// Of course, generics are also possible
function fn<T> (val:T) :T{
return val
}
Copy the code
Emmm, feel so water oh, I was wondering what else vuE3 didn’t cover before
Use vue3 vueX
This.$store is not the router in vue3, but useStore is used instead
import {useStore} from 'vuex'
let store=useStore()
Copy the code
Complete code, of course, this is only in VUe3 written in JS
// Code in vuex
import { createStore } from 'vuex'
export default createStore({
state: {
count:1.list: ['Joe'.'bill'].name:'Cathy'
},
mutations: {/ / method
setCount(state){
state.count++
},
setMsg(state,num){
state.count=num
}
},
getters: {// Calculate attributes
num(state){
return state.count+10}},actions: {// Implement the method of mutations, asynchronous operation
inCount(context){
context.commit('setCount')},setMsg({commit},num){
commit("setMsg",num)
}
}
})
Copy the code
<! -- Use it on other pages -->
<template>
<div class="home">
{{$store.state.count}}
<br>
<button @click="fn">Method of mutations</button>
<br>
{{num}}
<br>
<button @click="inCount">Method the actions</button>
<button @click="setMsg(50)">Actions method, passing values</button>
</div>
</template>
<script lang="ts">
import { computed, defineComponent } from 'vue';
import {useStore,} from 'vuex'
export default defineComponent({
name: 'Home'.setup(){
let store=useStore()
console.log(store.state.count)
/ / method
let fn=() = >{
store.commit('setCount')}// Calculate attributes
let num=computed(() = >{
return store.getters.num
})
// Implement the method of mutations, asynchronous operation
let inCount=() = >{store.dispatch('inCount')}
// Implement the method of mutations, asynchronous operation transfer value
// let setMsg=(num:number)=>{store.dispatch('setMsg',num)}
/ / method
let setMsg=(num) = >{store.commit('setMsg',num)}
return{
fn,
num,
inCount,
setMsg
}
}
});
</script>
Copy the code
If you use TS to write vuex in VUE3, you need to go to the official website to see what is introduced. Then the data defined in state should be declared in the interface state.
/ / code
import { InjectionKey } from 'vue'
import { Store,createStore } from 'vuex'
export interface State {
count:number,
list:string[],
name:string
}
export const key: InjectionKey<Store<State>> = Symbol(a)export const store= createStore<State>({
state: {count:1.list: ['Joe'.'bill'].name:'Cathy'
},
mutations: {/ / method
setCount(state:any){
state.count++
},
setMsg(state:any,num:number){
state.count=num
}
},
getters: {// Calculate attributes
num(state:any){
return state.count+10}},actions: {// Implement the method of mutations, asynchronous operation
inCount(context){
context.commit('setCount')},setMsg({commit},num){
commit("setMsg",num)
}
}
})
Copy the code
<template>
<div class="home">
{{$store.state.count}}
<br>
<button @click="fn">Method of mutations</button>
<br>
{{num}}
<br>
<button @click="inCount">Method the actions</button>
<button @click="setMsg(50)">Actions method, passing values</button>
</div>
</template>
<script lang="ts">
import { computed, defineComponent } from 'vue';
import {useStore} from 'vuex'
import { key } from '.. /store'
export default defineComponent({
name: 'Home'.setup(){
let store=useStore(key)
console.log(store.state.count)
/ / method
let fn=():void= >{
store.commit('setCount')}// Calculate attributes
let num=computed(() = >{
return store.getters.num
})
// Implement the method of mutations, asynchronous operation
let inCount=() = >{store.dispatch('inCount')}
// Implement the method of mutations, asynchronous operation transfer value
// let setMsg=(num:number)=>{store.dispatch('setMsg',num)}
/ / method
let setMsg=(num:any) = >{store.commit('setMsg',num)}
return{
fn,
num,
inCount,
setMsg
}
}
});
</script>
Copy the code
To be clear, I don’t think it is necessary to write VUex with TS. It is a lot of trouble to write
Good water oh, forget it, I will modify it later. Anyway, it is very basic, and there will be no problem if I write it according to my way. I am not in the mood to analyze the code recently