In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
Today, I would like to share with you the relevant knowledge points about how to use the slots of Vue and React. The content is detailed and the logic is clear. I believe most people still know too much about this, so share this article for your reference. I hope you can get something after reading this article. Let's take a look at it.
Slot, not found in React?
Slot is a very common function when using Vue. By defining the slot, the external content can be passed into the component and displayed to the specified location when the component is called. In Vue, slots are divided into default slots, named slots and scope slots. In fact, not only Vue, in fact, React also has a similar slot function, but the name is not called slot, below I will give an example to illustrate.
Default slot
Now the project needs to develop a card component, the card can specify the title, and then the card content can be customized by the user. At this time, the card content can be implemented using slots. Let's use Vue and React to achieve this function respectively.
Vue implementation
First implement a card component, as shown in the following code
{{title}} export default {props: {title: {type: String, default:''}
You can see that we used above, and this is the default slot for the component, and when using the component, the incoming content will be placed in its place.
Use defined card components externally
I will be placed in the default slot of the card component import MyCard from'.. / components/card' export default {components: {MyCard}}
As in the code above, you can use the default slot of the component to apply the external content to the specified location within the component.
React implementation
Although there is no concept of slots in React, you can also get the sub-elements inside the component tag through props.children, just like the sub-elements in the above code `tag. Through this, we can also achieve a function similar to the default slot in React. Let's take a look at the code.
Define Card components using React
Import React from 'react' export interface CardProps {title: string, children: React.ReactNode} export default function (props: CardProps) {return ({props.title} {/ * * each component can get props.children. It contains the content between the opening and ending tags of the component * /} {props.children});} import React from 'react' import Card from'. / components/Card' export default function () {return (I will be placed in the body area of the card component);}
Using Card components externally
Named slot
Continue to take the above Card component as an example, if our requirements have changed now, the title of the component can also use slots, then you can use named slots for Vue, and React also has a way to achieve it.
Vue implementation
The named slot of Vue mainly solves the situation where multiple slots are needed for a component. It is implemented by adding name` attribute to the component.
We modify the card component to meet the above requirements
{{title}} export default {props: {title: {type: String, default:''}
After the card component has been modified, let's adjust where the card component is used
Here is the title I will be placed in the default slot of the card component import MyCard from'.. / components/card'export default {components: {MyCard}} React implementation
React doesn't even have a slot, let alone a named slot, but it doesn't mean it can't be simulated. For the props of React, we can pass in not only a normal attribute, but also a function, so we can return JSX in the function passed in, thus realizing the function of named slot.
Modify the original Card components
Import React from 'react'export interface CardProps {title?: string, / / adds a renderTitle attribute of type Function renderTitle?: Function, children: React.ReactNode} export default function (props: CardProps) {const {title, renderTitle} = props / / if renderTtile is specified, renderTitle is used, otherwise the default title let titleEl = renderTitle? RenderTitle (): {title} return ({titleEl} {/ * * each component can get the props.children. It contains the content between the start and end tags of the component * /} {props.children});}
At this point, you can customize title externally.
Import React from 'react'import Card from'. / components/Card'export default function () {return ({return I am a custom title}} > I will be placed in the body area of the card component);} scope slot
Sometimes it is useful to give slot content access to data that is unique to subcomponents, which is why Vue provides scope slots. We continue to use the above Card component as an example, now I have developed a personnel information card component based on the above card component, users can directly use the personnel information card component to display personnel information in the interface, but in some business modules need to customize the way personnel information is displayed, then we need to use the scope slot.
Vue implementation
Implement the user information card component, which uses a scope slot
Name: {{userInfo.name}} gender: {{userInfo.sex}} Age: {{userInfo.age}} import CustomCard from'.. / card'export default {components: {CustomCard}, data () {return {userInfo: {name: 'Zhang San', sex: 'male', age: 25}
Use personnel information components externally
Name: {{userInfo.name}} Age: {{userInfo.age}} import UserCard from'.. / components/user-card'export default {components: {UserCard}} React implementation
In the named slot section, we simulate the named slot by passing a function to the component and then returning JSX in the function, so for the scope slot, we can still use this method, while the parameters passed by the scope slot can be replaced by passing parameters to the function.
Implement the personnel information card component
Import React, {useState} from 'react' import Card from'. / Card' interface UserCardProps {renderUserInfo?: Function} export interface UserInfo {name: string; age: number; sex: string;} export default function (props: UserCardProps) {const [userInfo] = useState ({name: "Zhang San", age: 25, sex: "male",}) Const content = props.renderUserInfo? (props.renderUserInfo (userInfo)): (name: {userInfo.name} Age: {userInfo.age} gender: {userInfo.sex}); return {content}}
Use personnel information card components externally
Import React from 'react' import UserCard, {UserInfo} from ". / components/UserCard"; export default function () {return ({return (name: {userInfo.name});}} >);} Context, provide/inject in React
Usually in project development, for state management between multiple components, Vuex will be used in Vue, redux or Mobx will be used in React, but for small projects, the use of these state management libraries seems to be overqualified, so how to complete data management without using these libraries? For example, the communication between grandparents and grandchildren, which is most frequently asked in the interview. We can use provide/inject in Vue and Context in React.
Suppose there is a scenario where the system now needs to provide a skin change function, and the user can switch skins, and now we use Vue and React to achieve this function respectively.
Provide/inject in Vue
In Vue, we can use provide/inject to pass values across multi-level components. Taking the above scenario as an example, we use provide/inject to implement the following
First, change the App.vue content to the following
Export default {data () {return {themeInfo: {theme: 'dark'}, provide () {return {theme: this.themeInfo}
Then use the following in any level of subcomponents
Export default {inject: ['theme']}
This enables theme to be shared among all sub-components.
Context in React
In Vue, we use provide/inject to achieve the function of passing values across components, and we also provide a similar function in React, that is, Context. Let's use Context to achieve the same function.
Create a new context directory under the project src directory, add the MyContext.js file, and then add the following
Import {createContext} from 'react'// defines MyContext, and specifies that the default theme is `light`export const MyContext = createContext ({theme:' light'})
MyContext provides a Provider through which theme can be shared to all subcomponents through Provider. Now we add MyContext.Provider to the common parent component of all components, such as App.js, to share the theme.
Import {MyContext} from'@ / context/MyContext';export default function () {const [theme, setTheme] = useState ('dark') return ()}
Then the defined theme theme can be used directly in all the subcomponents.
Import React, {useContext} from 'react'import {MyContext} from' @ / context/MyContext';export default function () {const {theme} = useContext (MyContext) return} without v-model, but does not affect the use
We know that both React and Vue are unidirectional data flow, that is, the data flow is transferred and updated from the outer layer to the inner layer components. For example, the following React code is the standard unidirectional data flow.
Import React, {useState} from "react"; export default function () {const [name] = useState ('Zijun') return} use v-model in vue
As in the code above, we are passing the external value to the input component through the value attribute, which is a simple one-way data flow. But when using Vue, there are two special syntax sugars, v-model and .sync, which give Vue components the ability to bind data in both directions, such as the following code
Export default {data () {return {name:''}
With v-model, when the user modifies the value of input, the value of the external name will also be modified synchronously. But this is the syntax sugar of Vue, React is not supported, so what should React do? At this point, consider that the custom v value model is actually implemented by defining the VMI attribute while listening for input events, such as this:
Export default {props: {value: {type: String, default:''}}, methods: {$_ handleChange (e) {this.$emit ('input', e.target.value)} looking for v-model alternatives in react
Similarly, although React does not have v-model syntax sugar, it can also achieve two-way data binding by passing in attributes and listening for events.
Import React, {useState} from 'react'export default function () {const [name, setName] = useState (' Zijun') const handleChange = (e) = > {setName (e.target.value)} return}
Editor just started to use react, feel that there is no v-model appears to be more troublesome, but trouble is trouble, code rewriting is also necessary. Just like the code above, each form element needs to listen for onChange events, which becomes more and more troublesome, so you can consider merging multiple onChange events into one, such as the following code
Import React, {useState} from 'react'export default function () {const [name, setName] = useState (' Zijun') const [sex, setSex] = useState ('male') const handleChange = (e:any, method: Function) = > {method (e.target.value)} return handleChange (e, setName)} > handleChange (e, setSex)} >} without instructions, I feel so confused
In Vue, we usually use template,template to draw pages, which provides a large number of instructions to help us complete business development, but in React we use JSX, and there are no instructions, so what should we do? Let's convert some of the most commonly used instructions in Vue into the syntax in JSX (note: JSX can also be used in Vue)
V-show and v-if
In Vue, we can hide the display element using v-show or v-if, of course, the two scenarios are different. V-show shows the hidden element by setting the display style of the element, while the v-if hidden element removes the element from the dom directly.
Take a look at the usage of v-show and v-if in Vue
Name: {{name}} {{dept}} export default {data () {return {name: 'Zijun', dept: 'Galactic Empire', showName: false, showDept: true}
Convert vshow _ show _ v _ if into syntax in JSX
Instructions exist in Vue to facilitate dynamic manipulation of data in template, but when we write JSX in React, we can use JS directly, so instructions do not need to exist, so how to replace the above in JSX
Import React, {useState} from 'react' export default function () {const [showName] = useState (false) const [showDept] = useState (true) const [userInfo] = useState ({name:' Zijun' Dept: Galactic Empire) return ({/ * * simulate v-show * /} {userInfo.name} {/ * * simulate v-show * /} {showDept? {userInfo.dept}: undefined})} v-for
V-for is used to traverse data in Vue, and when using v-for, we need to specify that the value of key,key is generally the id of the data or other unique and fixed value. There is key not only in Vue, but also in React. The meaning of key is basically the same, and both exist in order to optimize the virtual DOM diff algorithm.
Using v-for in Vue
{{item.name}} export default {data () {return {list: [{id: 1, name: 'Zijun'}, {id: '2Qing, name:' Zhang San'} {id: '3Qing, name:' Li Si'}]}
Using the alternative syntax of v-for in React
Although there is no v-for in react, JS can be used directly in JSX, so we can traverse the array directly.
Import React from 'react' export default function () {const data = [{id: 1, name: "Zijun",}, {id: "2", name: "Zhang San",}, {id: "3", name: "Li Si",},] Return ({data.map (item = > {return {item.name}})} v-bind and v-on
V-bind is dynamically bound to properties in Vue, and v-on is used to listen for events. Because React also has the concept of properties and events, we can also find alternatives in React.
Using v-bind and v-on in Vue
Export default {data () {return {value: 'Zijun'}}, methods: {handleInput (e) {this.value = e.target.value}
Look for alternatives in React
In Vue, the author separates events from attributes, but in React, events are also properties, so in this section we will not only look at how to use properties and events, but also learn how to customize events in React
Develop a CustomInput component
Import React from 'react' export interface CustomInputProps {value: string; / / you can see that onChange is a common function, which is also defined in the props of the component. OnChange: (value: string,event: React.ChangeEvent) = > void) | undefined } export default function (props: CustomInputProps) {function handleChange (e: React.ChangeEvent) {/ / props.onChange is an attribute and a custom event props.onChange & & props.onChange (e.target.value, e)} return ()}
Using CustomInput components
Import React, {useState} from 'react' import CustomInput from'. / components/CustomInput' export default function () {const [value, setValue] = useState (') function handleChange (value: string) {setValue (value)} return ()} these are all the contents of the article "how to use the slots of Vue and React". Thank you for reading! I believe you will gain a lot after reading this article. The editor will update different knowledge for you every day. If you want to learn more knowledge, please pay attention to the industry information channel.
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: 285
*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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.