More and more companies are embracing typescript because it makes code more readable and maintainable, and many companies now use typescript. Vue, the most popular framework in the country, has always been unfriendly to typescript extensions. Now with the help of extensions such as vue-class-Component and vue-property-decorator, We can also easily write our vUE applications using typescript+JSX templates in VUE.
start
To initialize the project with VUE -cli4, check typescript and create a new file named test. TSX to write the following code so that we can use JSX templates to write our code. However, some instructions in Vue are not available in JSX templates. Here are some examples of how some of vUE’s directives are used in JSX templates.
Calculate attributecomputed
And the listenerwatch
The listening event here is done with the vue-property-decorator’s Watch function.
v-show
,v-if
.v-for
attribute
Correction,v-show
Directives can be used directly in JSX templates.
The event processing
You can see that the one modifier event is handled with ~click, and there are other modifiers that need to be flexible. For details, see vue’s event & button modifiers in the render function. Also, blocking default events and preventing bubble events need to be handled in the event itself.
prop
attribute
Child componentsbutton.tsx
The parent componenttest.tsx
slot
attribute
Child componentsButton.tsx
The parent componenttest.tsx
You can see that slots pass values using scopedSlots. For details, see vue’s render function using slots
This.$scopedSlots as any is used to prevent typescript errors because typescript does not recognize the type of msgslot on this.$scopedSlots. A similar process is used to define events on vm.$refs, such as a handleEvent on ref, which can be triggered as follows.
const ref: any = this.$refs.ref;
ref.handleEvent()
Copy the code
$emit
use
Child componentsButton.tsx
The parent componenttest.tsx
For details, see @emit
Note here that if the parent component is calling the child component’s native event, it cannot be written directly
< test-button onMouseenter={handleEvent}> </ test-button >Copy the code
Instead of using nativeOn, use the following form:
< test-button nativeOn={{mouseEnter :handleEvent}}> </ test-button >Copy the code
For details, see VUE Deep Data objects
mixins
attribute
Mixin.tsx
test.tsx
As you can see, the vue-class-Component plugin is used to mix mixins. For more information, see mixins here and here
conclusion
We can use the JSX template better in Vue by referring to the render function & JSX on vue website. But use the JSX template to replace the template template, some instructions in using the JSX vue, a lot of orders need to be flexible, writing is also more cumbersome, vue some commands can rapid development of our program, however JSX template code hinting and improve the readability and maintainability of the code, enhance the development between the team.