I met TS
Course objectives
- TS introduction
- Install the typescript package
- TS hello World, type checking
- Introduction to learning Materials
knowledge
1. Introduction of TS
TypeScript is a strongly typed version of JavaScript. Then, at compile time, the types and specific syntax are stripped away, producing pure JavaScript code.
TypeScript is a superset of JavaScript, which means it supports all JavaScript syntax.
The strength of strongly typed languages lies in static type checking.
TypeScript is a language developed by Microsoft.
Vue3.0 is developed using TS.
Github open source project: github.com/Microsoft/T…
Born in October 2012.
Vscode is written in ts: github.com/Microsoft/v…
2. Install typescript packages
Packing:
yarn global add typscript
Copy the code
Check version:
tsc -V
Copy the code
Initialization:
tsc --init
Copy the code
3.TS hello World, type check
Syntax format:
function greeter(name:string) {
return `hello, world!${name}`
}
console.log(greeter('xu'))
document.body.innerHTML = greeter('xu')
Copy the code
4. Introduction of learning materials
Embrace a powerful TypeScript together – Ts + Vue complete tutorial: blog.csdn.net/suhuaiqiang…
Chinese manual: zhongsp. Gitbook. IO/typescript -…
Manuals in English: www.typescriptlang.org/docs/handbo…
Getting started: ts.xcatliu.com/
Decorator —- Yifeng Ruan: es6.ruanyifeng.com/#docs/decor…
Teaching ideas
Case assignments
2. Install TS environment and write hello World code 3. Explore the meaning of type checking. 4. Preview the meaning of each tsconfig.json attribute
Type checking
Course objectives
- The base type
- Types of assertions
- Significance of TS type check
- Introduction to learning Materials
knowledge
1. Basic types
Boolean, numbers, strings, arrays, primitives, enumerations, arbitrary values, null values, NULL, undefined, never, Object
/ / a Boolean
let isDone: boolean = true
/ / digital
let count: number = 1
/ / string
let username: string = 'admin'
/ / array
let list: number[] = [1.2.3]
let listPlus: Array<number> = [1.2.3]
/ / a Tuple Tuple
let x: [string, number]
x = ['hello'.10]
/ / the enumeration
enum Color { Red, Green, Blue }
let c: Color = Color.Green
/ / arbitrary value
let notSure: any = 1
notSure = 'xu'
notSure = true
/ / null
function greeter() :void {
console.log('hello')}//null
let u:undefined = undefined
let n:null = null
StrictNullChecks: false
let num:number = null
let str1:string = undefined
// The never type represents the types of values that never exist
// A function that returns never must have an unreachable end
function error(message: string) :never {
throw new Error(message);
}
// The inferred return value type is never
function fail() {
return error("Something failed");
}
// A function that returns never must have an unreachable end
function infiniteLoop() :never {
while (true) {}}//object
let obj:object = {}
Copy the code
Type assertion
Sometimes you’ll find that you know more about a value than TypeScript does. Usually this happens when you clearly know that an entity has a more exact type than its existing type.
Type assertions are a way of telling the compiler, “Trust me, I know what I’m doing.” Type assertion is like conversion in other languages, but without special data checking and deconstruction. It has no run-time impact, only at compile time. TypeScript assumes that you, the programmer, have done the necessary checks.
Type Assertion can be used to manually specify the Type of a value
Grammar:
< type > valueCopy the code
or
valueastypeCopy the code
Example:
(window as any).username = 'admin'
console.log((this as any).username)
Copy the code
3. Significance of TS type check
TS improves JS mainly by static type checking. What is the significance of static type checking? The standard answer is “static typing is better for building large applications.” Why is static typing good for building large applications? I conclude that there are two advantages.
First, static type checking can be an early fail, meaning that if you write code that doesn’t get executed, if a type mismatch occurs while you’re writing it, the language will catch it at compile time (and interpret execution, too, before it runs). For large applications, the test debug branch is difficult to cover, and much of the code may not be executed under all conditions. And if your code is so simple that any changes can be made to the UI, which is really not relevant to a large application, then static type checking really doesn’t work.
Second, type is the best comment. Static typing is friendly to reading code. For example, let’s take jQuery API Documentation, which everyone likes to use in jquery.Ajax. In this Documentation, the only parameter Settings of type Object is explained in detail, and it’s so complicated, If we were to look at the function declaration without documentation, it would be impossible for anyone to guess this usage correctly. For large applications, where methods are numerous and invocation relationships are complex, it is impossible for someone to meticulously document every function, so static typing is an important reminder and constraint. If you have code like jQuery where all the functions are apis, there are no internal functions at all, and the logic seems obvious, which is really not relevant for a large application, then static typing really doesn’t help reading the code. In general, modern programming language design, many features have very mature theoretical support, if we pay attention to the computer foundation, then some language applicable scenarios are like putting together building blocks, can be summarized in a few words. Like TS versus JS, just a single feature variation.
4. Introduction of learning materials
Basic types: zhongsp. Gitbook. IO/typescript -… The meaning of type check: www.jianshu.com/p/d2d15111f…
Teaching ideas
Case assignments
1. Practice type checking in TS 2. Use type assertions 3. Preview variable declarations
interface
Course objectives
- What is an interface
- Take a chestnut
- Optional attribute
- Read-only property
- Function types
knowledge
1. What is the interface
An interface simply specifies something. In the back, an interface refers to the API specified by both parties. In TS, an interface generally refers to what the variable owns. One of TypeScript’s core tenets is type-checking of the structure a value has. It is sometimes called “duck type discrimination” or “structural typing”. In TypeScript, interfaces name these types and define contracts for your code or third-party code. An interface is usually used to define a set of specifications. For example, usb interface is a specification for computer peripherals. No matter mouse, keyboard or USB disk, any peripherals that meet this specification can be inserted into this interface. Using a USB port reduces the coupling between peripherals such as a mouse and keyboard and a laptop.
2. Give me an example
// Define a person interface that describes the shape of an object: it must contain the name attribute and be of type string
interface Person {
name: string
}
// The Person interface is used just like a normal type
function greeter(person: Person) {
return `hello world!${person.name}`
}
// The xu object satisfies the constraints of the Person interface. If it does not, the compiler will immediately report an error, which is the point of type checking
let xu:Person = {
name: 'xu'
}
document.body.innerHTML = greeter(xu)
Copy the code
3. Optional attributes
Not all attributes in the interface are required. Some exist only under certain conditions, or not at all.
// Add a question mark to make it optional
interface Person {
name: string, age? : number }// The Person interface is used just like a normal type
function greeter(person: Person) {
return `hello world!${person.name}`
}
// The xu object may not contain the age attribute
let xu:Person = {
name: 'xu'
}
document.body.innerHTML = greeter(xu)
Copy the code
4. Read-only attribute
Some object properties can only change their value when the object is created. You can specify read-only properties with readonly before the property name
// Add a question mark to make it optional
interface Person {
readonly name: string,
age: number
}
// The Person interface is used just like a normal type
function greeter(person: Person) {
return `hello world!${person.name}`
}
// The xu object may not contain the age attribute
let xu:Person = {
name: 'xu'.age: 30
}
// You can change the age
xu.age = 31
// It is not possible to change the name, but it is not prevented by type checking
xu.name = 'xu'
document.body.innerHTML = greeter(xu)
Copy the code
5. Function types
Interfaces can describe the various shapes that objects in JavaScript can have. In addition to describing ordinary objects with attributes, interfaces can also describe function types. To use the interface to represent function types, we need to define a call signature for the interface. It is like a function definition with only the argument list and return value types. Each parameter in the parameter list needs a name and type. Since functions are also objects, we can also “specify” functions through interfaces.
// Function type
interface Greeter {
(name:string): string
}
let greeter: Greeter
// The Person interface is used just like a normal type
greeter = function (name:string) {
return `hello world!${name}`
}
document.body.innerHTML = greeter('xu')
Copy the code
Teaching ideas
## Case work
1. Research the meaning of interfaces 2. Define common object interfaces 3. 5. Preview the TS class (class)
Class to inherit
Course objectives
- What is the class
- Writing class
- What is inheritance
- Write the inheritance
knowledge
What is a class
All things are objects. In the object-oriented way, the objects in the real world are abstracted into objects, and the relations in the real world are abstracted into classes and inheritance, so as to help people realize the abstraction and digital modeling of the real world. The most basic unit of object orientation is the class. Class is an abstract concept that describes a Class of things. For example: cats, dogs, people. An object is an instantiation of a class. That is, a concrete individual member that fits the class description. What is a class? A class is not the existence of an entity, such as the mobile phone class. The mobile phone is not an entity, such as iPhone7 is an entity. Class: A class of things with the same attributes and skills (the variables following the class need to start with a capital letter). Object: a representation of a concrete class, an instance of a concrete object. Man is a class, Einstein is an object. A dog is a class, a ball is an object. Traditional JavaScript programs use functions and prototype-based inheritance to create reusable components, but it can be tricky for programmers familiar with the object-oriented approach because they use class-based inheritance and objects are built from classes. Starting with ECMAScript 2015, also known as ECMAScript 6, JavaScript programmers will be able to use a class-based object-oriented approach. With TypeScript, we allow developers to use these features now and compile JavaScript to run on all major browsers and platforms, without waiting for the next JavaScript version.
2. Write a class
// Define a class
class Greeter {
// Define class attributes
name: string
// constructor
constructor(name: string) {
this.name = name
}
// Define the method of the class
greet() {
// Use this when accessing the program inside
document.body.innerHTML = `hello world!The ${this.name}`}}// Construct an instance of the Greeter class using new. It calls the previously defined constructor, creates a new object of Greeter type, and initializes it by executing the constructor.
let greeter = new Greeter('xu')
// This object has the behavior of greeting
greeter.greet()
Copy the code
3. What is inheritance
One of the most basic patterns in class-based programming is to allow the use of inheritance to extend existing classes. Inheritance is the ability to take all the functionality of an existing class and extend it without having to rewrite the original class. New classes created by inheritance are called subclasses or derived classes. The inherited classes are called “base classes,” “superclasses,” or “superclasses.” The process of inheritance is the process of going from general to particular.
4. Write inheritance
// Define a class
class Person {
name: string
constructor(name: string) {
this.name = name
}
say() {
console.log(`The ${this.name}:hello! Everybody is good! `)}}The Teacher class inherits the Person class with the name attribute and the say method
class Teacher extends Person {
// Add your own course property
course: string
constructor(name:string, course:string) {
super(name)
this.course = course
}
// Add your own teach method
teach() {
// Call the inherited method
this.say()
// Access inherited properties
console.log(`The ${this.name}: The course I'm going to talk about isThe ${this.course}! `)}}let teacher = new Teacher('Xu Tongbao'.'Vue')
teacher.teach()
Copy the code
Teaching ideas
Case assignments
Study the meaning of class 2. Write class code 3. Study the meaning of inheritance 4
Public, private, and protected modifiers
Course objectives
- concept
- public
- private
- protected
- Why do I have to learn this
knowledge
1. The concept
There are three types of Access Modifiers available in TypeScript: public, private, and protected. By default, all properties and methods are public. Private properties or methods are private. Properties or methods that are protected cannot be accessed outside the class in which they are declared are protected. It is similar to private, except that it is also accessible in subclasses. Protected properties and access cannot be invoked on class instances
2.public
All properties and methods are public by default. It doesn't make any difference, so don't.Copy the code
// Define a class
class Person {
public name: string
constructor(name: string) {
this.name = name
}
public say() {
console.log(`The ${this.name}:hello! Everybody is good! `)}}Copy the code
3.private
// Define a class
class Person {
private name: string
constructor(name: string) {
this.name = name
}
private say() {
console.log(`The ${this.name}:hello! Everybody is good! `)}}let person = new Person('xu')
// An error occurs when accessing private attributes
console.log(person.name)
// An error occurs when accessing a private method
person.say()
Copy the code
Note: Derived classes also do not have access to the parent's private properties and methods!Copy the code
4.protected
Derived classes can access protected properties and access from the parent class.Copy the code
// Define a class
class Person {
protected name: string
constructor(name: string) {
this.name = name
}
protected say() {
console.log(`The ${this.name}:hello! Everybody is good! `)}}The Teacher class inherits the Person class with the name attribute and the say method
class Teacher extends Person {
// Add your own course property
course: string
constructor(name:string, course:string) {
super(name)
this.course = course
}
// Add your own teach method
teach() {
// Call the inherited method
this.say()
// Access inherited properties
console.log(`The ${this.name}: The course I'm going to talk about isThe ${this.course}! `)}}let teacher = new Teacher('Xu Tongbao'.'Vue')
teacher.teach()
Copy the code
5. Why are you learning this
Encapsulation is hidden object’s properties and implementation details, only made public interface, control the attributes of the program to read and modify the access level, the abstract data and behavior (or function), the combination of form an organic whole, namely the data and operation data of the source code for organic union, form a “class”, including data and function is a member of the class.
The purpose of encapsulation is to enhance security and simplify programming, so that consumers do not have to know the implementation details, but simply use the members of a class with specific access rights through an external interface. For example, the recorder is encapsulated chestnut, the internal structure is private, the user can not access, the play key, the fast forward key is common, the user can access.
Inheritance is the ability to take all the functionality of an existing class and extend it without having to rewrite the original class.
Without Protect, the properties and methods of the parent class would be public and private, and would be helpless if they were inherited but not exposed.
Teaching ideas
### Case work
Study the meaning of private attribute 2. Study the meaning of protected attribute 3. Write code to achieve encapsulation and inheritance 4. Preview three characteristics of object orientation
The class interface
Course objectives
- Class interface meaning
- Class interface instance
- Inherited interface
- Introduction to learning Materials
knowledge
1. The significance of class interface
Why do we need an interface, an implementation class for an interface? The interface is a specification. The goal of a unified standard is that everyone knows what it does, but they don’t have to know how to do it. Defining interfaces helps code specifications: For a large project, architects tend to define major interfaces or clean up unnecessary ones. The goal is to give developers a clear indication of what business needs to be implemented. At the same time, it can also prevent the unclear naming and code confusion caused by developers’ arbitrary naming, which affects the development efficiency. Interface is a standard, it is a convention, not an implementation, the copy is the purpose of the interface in order to standardize the implementation class, can need not tube concrete implementation class, so no matter how to implement because of you, I just know that implements this interface is your best, then you must have the method of degree, so I call this interface method is sure no problem. An interface is a high level of abstraction that specifies some behavior to be implemented or is merely a token.
2. Class interface instance
// The architect defines an interface that tells the programmer to develop a class according to the specification
interface PersonI {
name: string,
say():void
}
// A programmer spent three days developing a Teacher class, which is quite complex
class Teacher implements PersonI {
name: string
constructor(name: string) {
this.name = name
}
say() {
console.log(`hello! Everybody is good! I am aThe ${this.name}Teacher, today let's talk about TS! `)}}// Another programmer spent five days developing a Student class with more complex functionality
class Student implements PersonI {
name: string
constructor(name: string) {
this.name = name
}
say() {
console.log('Good teacher! I am aThe ${this.name}I wrote a code error, you help me look at it! `)}}// The Teacher and Student classes are part of the larger online education program
// Since both classes follow the same interface, they are easy to use
let teacher = new Teacher('xu')
teacher.say()
let student = new Student('Han Meimei')
student.say()
Copy the code
3. Inheritance interface
An interface is an abstraction of a class. In an inherited interface, one is an abstraction of a class and the other is more abstract than abstraction. This is the same as when an artist first draws an outline, and then sketches out the details bit by bit. In an inheritance hierarchy consisting of interfaces, the process from abstraction to concrete is seen from the top down. Inheritance allows us to preserve and extend the behavior defined in the parent interface. The whole inheritance hierarchy, in fact, is like a tree structure, and the deeper the tree goes, the more complex the behavior, the more things you can do. The upper layer is the abstraction of the commonality of the lower layer, and the lower layer is the evolution of the different dimensions of the upper layer. Because the granularity of abstraction of things is fine and thick.
// Any animal has a name
interface AnimalI {
name: string
}
// Not all animals can talk. Man can talk
interface PersonI extends AnimalI {
say():void
}
Birds can fly
interface BridI extends AnimalI {
fly():void
}
/ / the teacher
class Teacher implements PersonI {
name: string
constructor(name: string) {
this.name = name
}
say() {
console.log(`hello! Everybody is good! I am aThe ${this.name}Teacher, today let's talk about TS! `)}}/ / bird
class Brid implements BridI {
name: string
constructor(name: string) {
this.name = name
}
fly() {
console.log(`The ${this.name}Can fly! `)}}let teacher = new Teacher('xu')
teacher.say()
let brid = new Brid('the raven')
brid.fly()
Copy the code
4. Introduction of learning materials
Interface inheritance interface has practical implications: https://www.zhihu.com/question/48503724 inherited interface: https://zhongsp.gitbook.io/typescript-handbook/handbook/interfaces#ji-cheng-jie-kouCopy the code
Teaching ideas
Case assignments
1. Define class interface 2. Write the code of interface inheritance interface 3. Preview abstract classes
Abstract classes and polymorphism
Course objectives
- The difference between abstract classes and interfaces
- Abstract class instance
- polymorphism
- Introduction to learning Materials
knowledge
1. The difference between abstract classes and interfaces
Abstract class abstract methods must be decorated with the abstract keyword. If a class contains abstract methods, the class is called abstract, and the abstract class must be preceded by the abstract keyword. Abstract classes exist for inheritance. If a class inherits from an abstract class, the subclass must implement the parent class’s abstract methods. If a subclass does not implement the abstract methods of its parent class, it must also be defined as an abstract class.
The difference between abstract class and interface: abstract class can have method implementation, but the interface is completely abstract, there is no method implementation; Subclasses can inherit only one abstract class, and interfaces can be implemented by multiple implementations; Abstract methods can be public, protected, but interfaces can only be public, default; Abstract classes can have constructors, but interfaces cannot. Abstract classes are inherited as parent classes. The constructor of a derived class of an abstract class must call super(). Interfaces can be subclassed from other classes.
Neither an abstract class nor an interface can be instantiated. A class-type interface is actually an abstract type.
In my opinion, when using an interface of a class type, the interface of a class type is actually a subset of an abstract class. In addition to being defined and not implemented, as interfaces are, abstract classes can be partially implemented, and they can also use type modifiers.
An interface for a class type is used more as an abstract data type, usually an instance type of a class. An interface cannot contain a concrete implementation, and an abstract class can contain any function other than an abstract function. Abstract methods in abstract classes must be implemented in subclasses, and non-options in interfaces must be implemented when the interface is called. Abstract methods can be treated as instance methods of a class, adding access modifiers; But interfaces do not. An abstract class can have no abstract methods in it. However, classes with abstract methods must be declared as abstract classes.
A few considerations for abstract classes:
1. Abstract classes use the abstract modifier
2. Abstract methods can only be in abstract classes
3. Abstract classes cannot be instantiated
4. Abstract methods have no method body
5. Abstract classes cannot be static or sealed
6. A subclass must override all the abstract methods of its parent unless the subclass is also abstract
7. Abstract classes can have ordinary methods
8. An abstract class can have constructors
9. Abstract methods in abstract classes are intended to constrain the method form of subclasses.
2. Abstract class instances
// Abstract class, used for inheritance, cannot be instantiated
abstract class Person {
name: string
constructor(name: string) {
this.name = name
}
say() {
console.log(`hello! Everybody is good! I am aThe ${this.name}! `)}// Abstract methods
abstract job(): void
}
class Teacher extends Person {
constructor(name: string) {
super(name)
}
job() {
console.log('My job is to teach! ')}}class Student extends Person {
constructor(name: string) {
super(name)
}
job() {
console.log('My job is to study! ')}}let teacher = new Teacher('Xu Tongbao')
teacher.say()
teacher.job()
let student = new Student('Han Meimei')
student.say()
student.job()
Copy the code
3. The polymorphism
Interviewer: What is polymorphism? Pig teammate: various forms, gas, liquid, solid ~ interviewer: go out! now!
In simplest terms, a reference to a parent type refers to an object of a child type. To use a more common phrase: the same operation on different objects can produce different effects. That’s polymorphism. Multiple forms, in which different objects respond differently to the same operation. Polymorphism is the ability to have many different manifestations or forms of the same behavior. Polymorphism is the same interface, using different instances to perform different operations. The final manifestation of polymorphism is that a parent reference variable can point to a subclass object. The premise of polymorphism is that there must be a child parent class relationship or class implementation interface relationship, otherwise the polymorphism cannot be completed. When a method is called using a polymorphic parent reference variable, the method overridden by the subclass is called. Polymorphic: The same operation on different objects can be interpreted differently, resulting in different execution results. At run time, methods that implement derived classes can be called with Pointers to the base class.
The parent class type variable name = new subclass type (); Variable name. Method name ();
let teacher: Person = new Teacher('Xu Tongbao')
teacher.job()
Copy the code
Person Person = new Student; But what does this polymorphism do? And why are we so polymorphic?
First, encapsulation and inheritance: Encapsulation is surrounded by the process and data access to data only through defined interfaces, he hide implementation details of a picture, such as you to achieve a class in Java, this class provides some function method, you just need to know what you need to pass parameters, can achieve what kind of effect, implementation details defined in the class. This makes code modular; Inheritance extends existing code modules with the goal of code reuse.
So polymorphisms can be decoupled in addition to code reuse. But why decouple? Coupling is module between modules, the correlation between code, through the analysis of the system is decomposed into him a a child module, module provides stable interface, achieve the purpose of reduce coupling system, try to use module interface between module module access, rather than random reference other module member variables.
What are the benefits of polymorphism?
There are two benefits:
- Instead of writing function calls for every derived class, the application just needs to process the abstract base class. Greatly improve program reusability. / / inheritance
- Functions of derived classes can be called by methods or reference variables of the base class. This is called backward compatibility, which improves scalability and maintainability. // The true function of polymorphism,
4. Introduction of learning materials
What is polymorphism: blog.csdn.net/qq_28081081… Polymorphic seconds understand encyclopedia: baike.baidu.com/item/%E5%A4…
Teaching ideas
Case assignments
1. Define abstract class 2. Learn the concept of polymorphism 3. Preview the generic
The generic
Course objectives
- Meaning of using generics
- A generic interface
- A generic class
- Introduction to learning Materials
knowledge
The meaning of using generics
A Generics is a type variable, a special type of variable that is used only to represent a type, not a value. T is about the first letter of the word “Type”. A type of variable. Friends who have not been very long. Casual acquaintance means a friend who is not very close. In general, it means to talk about it in general or on the surface. Generics: Postpone specifying specific types until object creation or method invocation time. Benefits: Much cleaner code [no casts]. The program is more robust. Readability and stability [the type is qualified when the collection is written].
Generics, or parameterized types. That is, a type is parameterized from an original concrete type, similar to a variable parameter in a method, in which the type is also defined as a parameter (called a type parameter), and then passed in the concrete type (type argument) when used or called. K: Key N: Number T: Type V: Value
The value of using generics: (1) it is suitable for multiple data types to execute the same code (code reuse) (2) The type in a generic is specified at the time of use, type safety, the compiler will check the type
function identity<T> (arg: T) {
return arg
}
console.log(identity(1))
console.log(identity<string>('a'))
console.log(identity(true))
Copy the code
2. Generic interfaces
interface IEcho<T> {
(arg: T): T
}
function echo<T> (arg: T) {
return arg
}
let myEcho: IEcho<number> = echo
let myEcho2: IEcho<string> = echo
console.log(myEcho(1))
console.log(myEcho2('a'))
Copy the code
3. A generic class
/ / a generic class
class ArrayList<T> {
array: T[] = []
size: number
add(item: T) {
this.array.push(item)
this.size = this.array.length
}
// Share one set of logic
print() {
console.log('All data:The ${this.array.join(' ')}`)}}// The type is specified when the object is created
let numberList = new ArrayList<number>()
numberList.add(1) // If it is an error type, an error is reported
numberList.add(2)
console.log(numberList.size)
numberList.print()
let strList = new ArrayList<string>()
strList.add('xu')
strList.add('xu')
strList.add('hello')
console.log(strList.size)
strList.print()
Copy the code
4. Introduction of learning materials
Liao Xuefeng what is generic: www.liaoxuefeng.com/wiki/125259…
For an in-depth understanding of Java generics: www.sohu.com/a/245549100…
Teaching ideas
Case assignments
1. Define generic classes 2. Learn how generics are used 3. Preview decorators
A decorator
Course objectives
- The meaning of decorators
- Class decorator
- Vue-property-decorator decorator pseudocode
- Introduction to learning Materials
knowledge
1. The meaning of decorators
The Decorator proposal has been extensively revised and is not yet finalized, so I wonder if the syntax will change again.
A Decorator is a class-related syntax for annotating or modifying classes and class methods. Many object-oriented languages have this capability, and there is currently a proposal to introduce it into ECMAScript.
A decorator is a function named @ +. It can precede the definition of classes and class methods.
They not only increase the readability of the code and express the intent clearly, but also provide a convenient means to add or modify the functionality of the class.
Decorator is a new syntax in ES7, currently in phase 2 proposal. As it is called “Decorator,” it can wrap objects by adding the @ method name and then return a wrapped object. Decorators include classes, properties, methods, etc.
The addition of definitions and operations on class objects (such as class and extends) in ES6 makes it less elegant to share or extend methods or behaviors across multiple classes. That’s when we need a more elegant way to get things done.
Note that the decorator changes the behavior of the class at compile time, not run time. This means that the decorator can run the code at compile time. That is, decorators are essentially functions that are executed at compile time.
2. Class decorator
The Teacher and Student classes are decorated with new methods!
const mixins = (obj: IObj) = > (target:any) = > {
Object.assign(target.prototype, obj)
}
interface IObj {
eat(): void
walk(): void
}
let obj: IObj = {
eat() {
console.log('eat')},walk() {
console.log('walk')
}
}
@mixins(obj)
class Teacher {
name: string
constructor(name: string) {
this.name = name
}
job() {
console.log('teach')
}
}
@mixins(obj)
class Student {
name: string
constructor(name: string) {
this.name = name
}
job() {
console.log('learning')}}let teacher = new Teacher('Xu Tongbao')
teacher.job()
//@ts-ignore
teacher.eat()
let student = new Student('Han Meimei')
//@ts-ignore
student.walk()
Copy the code
3. Vue-property-decorator pseudocode
Write the pseudo-code for the decorator provided by the VUe-property-decorator package: Componetn, Prop, Emit
// Class decorator that takes an object parameter, which can contain a component property
// The value of the components property expresses the component to be used
const Component = (obj: IComponent) = > (target: any) = > {
Object.assign(target.prototype, obj)
}
// A decorator for a class property that can be set to default values
const Prop = (obj: IProp) = > (target: any, key: string) = > {
target[key] = obj.default
}
// Class method decorator. When a class method fires, it calls the method passed by the parent component with the return value of the class method
const Emit = (method: string) = > (target: any, key: string, descriptor: any) = > {
let oldValue = descriptor.value
descriptor.value = function() {
let result = oldValue.apply(this.arguments)
console.log('trigger the method passed by the parent component:${method}(The ${JSON.stringify(result)}) `) } } interface IComponent { components? : object } interface IProp {default: any
}
@Component({
components: {
Header: 'components'}})class Home {
@Prop({ default: 'zhanwei'}) name! : string @Emit('onClick')
handleClick(id: number) {
console.log('Click event'.this.name)
return { id }
}
}
let home = new Home()
//@ts-ignore
console.log(home.components)
console.log(home.name)
home.handleClick(1)
Copy the code
4. Introduction of learning materials
Ruan Yifeng explains decorators es6.ruanyifeng.com/#docs/decor…
Decorator proposal: TC39. Es /proposal-de…
Teaching ideas
Case assignments
1. Define class decorators 2. Define class attributes and class methods decorators 3
Vue – based on component class)
Course objectives
- The scaffold
- Vue – class – what is component
- How do you use the vue – class – component
- Introduction to learning Materials
knowledge
1. The scaffold
Error: Missing trailing comma Missing semicolon Missing semolon Json file to add the following code to the rules field:
"trailing-comma": [false]."semicolon": [false]
Copy the code
2. Vue – class – what is component
Vue-class-component is a typescript support library for VUE from Rain Creek. Vue-class-component is the official vUE library that writes components as classes. Vue-class-component highlights several uses: Methods can be declared directly as a class member method. Computed properties can be declared as a class attribute accessor. Data data can be declared as a class attribute. Avoid using these reserved names when declaring custom methods.
3. The vue – class – how do you use the component
Add, add, subtract, subtract:
<template>
<div>
<div>{{count}}</div>
<button @click="handleSub">Reduction of</button>
<button @click="handleAdd">add</button>
</div>
</template>
<script>
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
class Login extends Vue {
count = 0
handleSub() {
this.count--
}
handleAdd() {
this.count++
}
}
Copy the code
v-model:
<template>
<div>
<input v-model="username">
</div>
</template>
<script>
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
class Login extends Vue {
username = 'admin'
}
export default Login
</script>
Copy the code
Mount life cycle:
<template>
<div>
1
</div>
</template>
<script>
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
class Login extends Vue {
mounted () {
console.log('Mount done')}}export default Login
</script>
Copy the code
Calculated attributes:
<template>
<div>
{{double}}
</div>
</template>
<script>
import Vue from 'vue'
import Component from 'vue-class-component'
@Component
class Login extends Vue {
count = 1
get double() {
return this.count * 2}}export default Login
</script>
Copy the code
4. Introduction of learning materials
Vue-class-component official website (without Chinese version) : class-component.vuejs.org/
Basic usage: www.jianshu.com/p/2f65e9dea…
Teaching ideas
Case assignments
1. Build the project through scaffolding 2. Make addition, subtraction and 3
Vue – property – the decorator
Course objectives
- Vue – property – the decorator is what
- Vue-property-decorator passes values to parent components
- Introduction to learning Materials
knowledge
1. The vue – property – is a decorator
Vue-property-decorator community; Vue-class-component official product. Vue-property-decorator relies heavily on vue-class-Component to extend operators such as @prop, @emit, etc. Vue-property-decorator is written by kaorun343 (Japan).
2. Vue-class-component transmits values to parent and child components
Use the Component decorator to register child components.Copy the code
The parent component:
<template>
<div>
<Icon :name="visible ? 'show' : 'hide'" @onClick="handleVisible"></Icon>
</div>
</template>
<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
import Icon from '.. /components/Icon.vue'
@Component({
components: {
Icon
}
})
class Login extends Vue {
visible = false
handleVisible(payload:object) {
this.visible = !this.visible
}
}
export default Login
</script>
Copy the code
Use the Prop decorator to get the value passed by the parent component. You can define default values using default. Use an exclamation mark to ignore warnings that class attributes are not initialized. Use the Emit decorator to trigger the parent component’s method with the method name in parentheses and the return value of the function as the payload.
Child components:
<template>
<span :class="[`icon iconfont icon-${name} ${className}`]" @click="handleClick"></span>
</template>
<script lang="ts">
import { Vue, Component, Prop, Emit } from 'vue-property-decorator'
@Component
class Icon extends Vue {
@Prop({ default: 'zhanwei'}) name! : string @Prop({default: ' '}) className! : string @Emit('onClick')
handleClick() {
return { id: 2}}}export default Icon
</script>
Copy the code
3. Introduction of learning materials
Decorator decorator decorator decorator decorator decorator decorator decorator decorator decorator decorator
Teaching ideas
Case assignments
1. Use vue-property-decorator to pass parent-child component values 2. 3. Preview vuex-class
Vuex – class basis
Course objectives
- Vuex – what is the class
- Vuex-class Synchronizes the modification repository
- Vuex-class Asynchronous modify repository
- Introduction to learning Materials
knowledge
1. The vue – what is the class
Vuex-class wraps the way vuex is written, simplifying code. Vuex-class makes it easier to combine vuex with vuE-class-Component. The author of Vuex-Class is KTSN (Singapore).Copy the code
2. Vuex-class synchronously modifies the warehouse
Use the warehouse for addition and subtraction. @State @MutationCopy the code
Warehouse:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
interface Payload {
key: string,
value: any
}
export default new Vuex.Store({
state: {
count: 0
},
mutations: {
setState(state:any, payload:Payload) {
state[payload.key] = payload.value
}
},
actions: {},modules: {}})Copy the code
Page:
<template>
<div>
<div>{{count}}</div>
<button @click="handleSub">Reduction of</button>
<button @click="handleAdd">add</button>
</div>
</template>
<script lang="ts">
import Vue from 'vue'
import Component from 'vue-class-component'
import { State, Mutation } from 'vuex-class'
@Component
class Login extends Vue {
@State('count') count! :number @Mutation('setState') setState! :Function
handleSub() {
let count = this.count - 1
this.setState({ key: 'count'.value: count })
}
handleAdd() {
let count = this.count + 1
this.setState({ key: 'count'.value: count })
}
}
export default Login
</script>
Copy the code
3. Vuex-class asynchronously modifies the warehouse
@Action
Copy the code
Get data:
<template>
<div class="m-main m-home">
<Sidebar></Sidebar>
<List></List>
</div>
</template>
<script lang="ts">
import { Vue, Component } from 'vue-property-decorator'
import { Action } from 'vuex-class'
import Sidebar from '.. /components/Sidebar.vue'
import List from '.. /components/List.vue'
@Component({
components: {
Sidebar,
List
}
})
export default class Home extends Vue {
@Action('list') list:any
mounted() {
this.list()
}
}
</script>
<style>
</style>
Copy the code
Submit the action with the payload:
<script lang="ts">
import { Vue, Component, Prop } from 'vue-property-decorator'
import { State, Action } from 'vuex-class'
@Component
export default class MyBookItem extends Vue { @Prop() book! :any @State(state= >state.myBooks) myBooks! : any[] @Action('myBooksAction') myBooksAction! :Function
handleAdd(id:number) {
this.myBooksAction({ data: { id, operation: 'add' }, method: 'patch'})}handleSub(id:number) {
this.myBooksAction({ data: { id, operation: 'sub' }, method: 'patch'})}handleInput(id:number, e:any) {
let myBooks = this.myBooks
let count = e.target.value.replace(/[^\d]/g.' ') - 0
if (count === 0) {
count = 1
}
this.myBooksAction({ data: { id, operation: 'inputCount', count }, method: 'patch'})}handleChecked(id:number, e:any) {
this.myBooksAction({ data: { id, operation: 'checked'.checked: e.target.checked }, method: 'patch'})}handleDelete(id:number) {
this.myBooksAction({ data: { ids: [id] }, method: 'delete' })
}
}
</script>
Copy the code
4. Introduction of learning materials
Vuex-class official website: github.com/ktsn/vuex-c…
Teaching ideas
Case assignments
1. Compile synchronous and asynchronous events using vuex-class. 2. Prepare the react + ts