Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to use JSX in Vue

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article focuses on "how to use JSX in Vue". Interested friends may wish to have a look at it. The method introduced in this paper is simple, fast and practical. Let's let the editor learn "how to use JSX in Vue".

Brief introduction

Let's give an example of why JSX is good.

We want to build a component that can be normal single-line text input or multiple-line input (text area). Our template declaration might look like this.

Typeof10;//= > 'number'typeof'Hello';//= >' string'typeoffalse;//= > 'boolean'typeof {object'typeofundefined;//= 1}; / / = >' object'typeofundefined;//= > 'undefined'typeofSymbol (); / / = >' symbol'

As you can see from the code snippet above, we will soon encounter some problems, such as repeating code, and so on. Imagine that the various attributes listed above in input must be supported. This little clip above will grow and become a difficult nightmare to maintain.

To solve this problem, we need to use Vue for degradation, so we need to use an internal API that is close to Vue to solve this problem.

Render () method

Note: this is not to say that there is no easy way to deal with the above problem without JSX, just that moving this logic to the render () method with JSX makes the component more intuitive.

Each component we create in Vue has a render method. This is where Vue chooses the rendering component. Even if we don't define this method, Vue will do it for us.

This means that when we define a HTML template in Vue, Vue's template compiler compiles it into a createElement function that takes several parameters and returns the result from the render function.

To fix the code in the previous section, we removed the template attribute or template tag and defined the render () method on the component. If the render method is defined on the component, Vue ignores the template definition.

ClassCat {} constmyCat=newCat (); myCatinstanceofCat;//= > true

The above code does several things:

The render method gets a createElement helper from Vue.

We define our tags programmatically.

Then, we create the tag and pass its attributes, classes, and so on as objects. There are a number of options that we can pass to createElement.

We return to the newly created element for rendering.

Each template we define for the Vue component is converted to a render method that returns the createElement function. For this reason, the render method takes precedence over the template definition.

For example:

/ / HTML

Onlyyoucanstopforestfires

The template compiler will convert the above HTML to:

... render (createElement) {returncreateElement ('div', {}, createElement (' packs, {}, 'Onlyyoucanstopforestfires'))}.

Now you might ask this question: "isn't that good for readability?" The answer is yes. Once we have defined components with many element nesting levels or multiple sibling elements, we will encounter this new problem.

This is the reason for the emergence of JSX, it can solve such problems very well.

What is JSX?

JSX is a term coined by the Facebook engineering team.

JSX is a XML-like syntactic extension of JavaScript without any defined semantics.

JSX is not intended to be implemented by an engine or browser. Instead, we will use transposers such as Babel to convert JSX into regular JS.

/ / this line is a sample constheading=WelcometoScotch of JSX

Basically, JSX allows us to use Html-like syntax in JS.

Configure Vue to use JSX

If you are using Vue-cli greater than or equal to version 3. 0, you can use the syntax of JSX directly.

If you are using an older version of Vue-cli that does not support JSX, you can add it by installing babel-preset-vue-app and adding it to your .babelrc file.

# Usingnpmnpminstall--save-devbabel-preset-vue-app#Usingyarnyarnadd--devbabel-preset-vue-app

In the .babelrc file, add:

{"presets": ["vue-app"]}

We can now use JSX in the render function of the component.

What you should pay attention to when using JSX in Vue

There are several points to pay attention to when using JSX in Vue.

To listen for events in JSX, we need the "on" prefix. For example, use onClick for a click event.

Render (createElement) {return ()}

To modify an event, use the

Render (createElement) {return ()}

Bind variables, note that you are not using:

Render (createElement) {return ()}

Set the HTML string to the content of the element, using domPropsInnerHTML instead of v-html

Render (createElement) {return ()}

We can also expand a large object:

Render (createElement) {return ()}

Using JSX in render

Go back to our original "TextField" component. Now that we have enabled JSX in the Vue application, we can do so.

Render (createElement) {constinputAttributes= {class:'input-fieldhas-outline',//classdefinitiononClick:this.handleClick//eventhandlerbackdrop:false//customprop} constinputMarkup=this.multiline?:returninputMarkup}

Import Vue JS components

Another benefit of using JSX in Vue is that we no longer need to register every component we need. We just import and use.

Import {Button} from'../components'exportdefault {render (createElement) {returnEdit}}

How to use JSX with TypeScript

TypeScript is used as a mechanism for adding type checking to JavaScript. To support TypeScript in JSX, you need to modify the tsconfig.json.

To enable JSX in TypeScript, first save the file as a .tsx file, and then modify the tsconfig.json to include:

{"compilerOptions": {.... "jsx": "preserve",}}

Setting the jsx option to "preserve" means that TypeScript should not handle JSX. Doing so allows Babel to control all JSX and TypeScript persistence types because it does not yet support Vue JSX.

Then create a jsx.d.ts file in the project and add a TypeScript JSX declaration for Vue.

ImportVue, {VNode} from'vue'declareglobal {namespaceJSX {interfaceElementextendsVNode {} interfaceElementClassextendsVue {} interfaceElementAttributesProperty {$props: {}} interfaceIntrinsicElements {[elemName:string]: any}

Make sure that TypeScript can load the declaration file. Alternatively, you can add the auto-load feature to tsconfig.json in the following ways:

{"compilerOptions": {. "typesRoot": [". / node_modules/@types", ". / types"]} at this point, I believe you have a deeper understanding of "how to use JSX in Vue". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report