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

Case Analysis of using skills of Vue

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces the relevant knowledge of "case analysis of Vue use skills". The editor shows you the operation process through the actual case. The operation method is simple, fast and practical. I hope this "case analysis of Vue use skills" article can help you solve the problem.

1. Restrict an prop to a list of types

When we use prop, we may sometimes need to determine whether the prop is within our specified range (or within the specified value). At this point, we can use the validator option in the prop definition to limit a prop type to a specific set of values.

Export default {name: 'Test', props: {name: {type: String,}, size: {type: String, validator: s = > [' small', 'middle'] .requests (s)}

This validation function accepts a prop and returns true or false if the prop is valid or invalid. I usually use this method when passing in true or false alone to control that certain conditions do not meet the requirements.

2. Use quotation marks to listen for nested attributes

You may have used watch to listen to a property, but you may not know this, so we can easily listen for nested values directly by using quotation marks

Watch {'obj.message.name' () {/ /...}} 3, know when to use v-if

Sometimes using v-if, often using v-show instead, will have higher performance.

When v-if is turned on or off, it creates and completely destroys the element. Instead, v-show creates the element and leaves it there, hiding it by setting its style to display: none, which is more efficient if the component you want to switch is expensive to render, especially for complex components or pages. V-show is recommended.

Conversely, if you don't need to execute expensive components immediately, you can use v-if so that it skips rendering it and makes the page load faster.

4. Abbreviation of a single scope slot

Scoped slots are interesting, but in order to use them, you must also use a lot of template tags. Fortunately, there is an abbreviation that allows us to get rid of it, but only if we use a single scope slot.

You may have used it like this.

Do not use template

It's simple, straightforward, and amazing.

5. Mix local and global style together

In general, when dealing with styles, we want them to work only within the current component

.content {background: green;}

However, if necessary, you can also add a non-scoped style block to add a global style

/ * Global * / .content p {font-size: 12px;} / * valid within this component * / .content {background: green;}

It is important to note that global styles are dangerous and difficult to track. But sometimes they are the perfect escape hatch, just what you need.

6. Override the style of the subcomponent

Scoped CSS is great at keeping content clean and doesn't introduce styles into other components of the application. But sometimes we need to override the style of a subcomponent and jump out of that scope.

Vue has a deep selector to accomplish the above functions.

.my-content > .child-component {font-size: 16px;}

Note: if you use a CSS preprocessor like LESS, you may need to use / deep/ instead

.my-content / deep/. Child-component {font-size: 16px;} 7, how to create a responsive variable outside of Vue

If you get a variable from outside Vue, it's good to make it reactive. In this way, we can use it in computed props, watch, and anywhere else, and it works just like any other state in Vue.

If we use the option API, all we need is to put it in the data section of the component

Const externalVariable = getValue (); export default {data () {return {reactiveVariable: externalVariable,};}}

If you use Vue3's combined API, you can use ref or reactive directly

Import {ref} from 'vue'; / / can be done entirely outside the Vue component const externalVariable = getValue (); const reactiveVariable = ref (externalVariable); / / use ref to make it responsive

Use reactive instead

Import {reactive} from 'vue'; / / can be done entirely outside the Vue component const externalVariable = getValue (); / / reactive only works on objects and arrays const anotherReactiveVariable = reactive (externalVariable)

If you are still using Vue2, you can use observable instead of reactive to achieve exactly the same result

Import Vue from 'vue' / / can be completed completely outside the Vue component const externalVariable = getValue (); const anotherReactiveVariable = Vue.observable (externalVariable); 8. Deconstruction in v-for

Do you use deconstruction in v-for?

/ / users: [{name:'leo',id:'1'}, {name:'lion',id:'2'}] {{name}}

More widely known is that indexes can be fetched from v-for by using such tuples

{{index + 1}} = > {{movie}}

When using an object, you can use key like this

{{key}}: {{value}}

You can also combine these two methods to get the key and the index of the attribute

{{index + 1}} = > {{key}}: {{value}} 9, cycle within the specified range

V-for allows us to traverse the array and also allows us to traverse a range

Item {{num}}

Render result

Item 1

Item 2

Item 3

Item 4

Item 5

Item 6

Here's a note: when we use v-for to iterate through a range, it starts at 1 and ends with the number we specify.

10. Steal prop type

We copy prop types from a child component just to use them in a parent component. But it's often better to steal these prop types than to just copy them. What do you mean?

For example, we use a List component in a component

{{title}}

In order for it to work, we need to add the correct prop type and copy it from the List component

Import List from'. / List' Export default {components: {List}, props: {listType: {type: String, required: true,}, listSize: {type: String, default: 'medium', validator: size = > [' small', 'medium',' large', 'xMuthlarge'] .colors (size), listName: {type: String Default: 'list',}, title: {type: String, required: true,}

Do you find it troublesome when you look at it?

When the prop type of the List component is updated, we will certainly forget to return the component and update them. Over time, errors are introduced when the prop type of the component begins to deviate from the prop type in the List component.

So, that's why we steal the prop type of the component, as follows

Import List from'. / List';export default {components: {List}, props: {... List.props, / / steal the prop of List. There is no need to list title: {type: String, required: true,}

Isn't that a lot easier?

Except in the above example, we add List to the beginning of each prop name. So we have to do some extra work to achieve this.

Import List from'. / List'; const listProps = {}; Object.entries (List.props). ForEach ((key, val) = > {listProps [`list$ {key.toUpperCase ()} `] = val;}); export default {components: {List}, props: {... listProps, title: {type: String, required: true,}

Now, if the prop type in the List component is modified, our component will remain up to date. But what if a prop type is added or removed from the List component? To deal with these situations, we can use v-bind and a computational prop to stay dynamic.

11. Detect clicks outside (or inside) the element

When we need to detect whether a click occurs inside or outside a particular element el, the usual method

Window.addEventListener ('click', e = > {/ / get the clicked element const currtentEl = e.target; / / detect whether it is inside or outside the el element if (el.contains (currtentEl)) {/ / click} else {/ / outside the el} in the el); 12. Call a method from outside the component

We can call a method from the outside of a component by giving it a ref

/ / call the method this.$refs.child.method () of the subcomponent in this component

Typically, we use props and events to communicate between components. Props is sent to the child component, and events is uploaded to the parent component

/ / Child.vueexport default {props: ['trigger'], watch: {shouldCallMethod (newVal) {if (newVal) {/ / Call the method when the trigger is set to `true` this.method ();}

This works fine, but can only be used on the first call. If you need to trigger this operation multiple times, you must clean up and reset the state. The logic is as follows

The parent component passes the true to the trigger prop

The Watch is triggered, and the Child component calls the method

The child component issues an event telling the parent component that the method has been successfully triggered

The Parent component resets trigger to false, so we can start all over again

On the contrary, if we set a ref on the subcomponent, we can call the method directly (as in the original way), we broke the "props down, events up" rule, we broke the encapsulation, but it was clearer and easier to understand.

13. Listen for arrays and objects

Sometimes watcher doesn't trigger correctly, and in many cases it's because we try to listen to arrays or objects, but don't set deep to true.

Export default {name: 'namesChange', props: {names: {type: Array, required: true,},}, watch: {names: {/ / this will let Vue know to look inside the array. If you do not add it, you cannot do deep snooping deep: true, handler (newVal,oldVal) console.log (' The list of names has changeable') }

Use in vue3

Watch (names, (newVal,oldVal) = > {console.log ('The list of names has changeable');}, {deep: true,}); 14. Another use of the template tag

The template tag can be used anywhere in the template to better organize the code. Sometimes it simplifies v-if logic, and sometimes it uses v-for. As follows, we have several elements that all use the same v-if condition

{{title}} {{subheading}}

If we take a closer look at the above code, we will find that some elements are displayed under the same conditions as hidden, but this is not friendly, and it can be a bad situation on a larger, more complex component.

We can use template tags to group these elements (elements with consistent v-if conditions) and promote v-if to the template template itself for optimization

{{title}} {{subheading}}

Now it looks much clearer and easier to understand, and what it is doing is clear at a glance.

15. Better ways to deal with errors (and warnings)

We can provide a global custom handler for errors and warnings in Vue

/ / Vue 2Vue.config.errorHandler = (err) = > {alert (err);}; / / Vue 3const app = createApp (App); app.config.errorHandler = (err) = > {alert (err);}

Of course, you can also use them to handle errors more elegantly to get a better user experience. For example, if an error is not handled, the application does not crash directly, but displays a complete error screen that prompts the user to refresh or try something else.

This is the end of the introduction to "case study of Vue usage skills". Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

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