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)05/31 Report--
This article mainly introduces the relevant knowledge of "what are the techniques used by Vue". The editor shows you the operation process through actual cases, the operation method is simple and fast, and it is practical. I hope this article "what skills are used by Vue" can help you solve the problem.
1. Restrict an prop to a list of types
Using the validator option in the prop definition, you can restrict an prop type to a specific set of values.
Export default {name: 'Image', props: {src: {type: String,}, style: {type: String, validator: s = > [' square', 'rounded'] .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.
Button types or warning types (information, success, danger, warning) are the most common uses. Color is also a good use.
2. Default content and extension point
Slots in Vue can have default content, which allows us to make components that are easier to use.
Click me
My favorite use of default slots is to use them to create extension points.
We can take any part of the component and package it in a slot, and on the outside we can cover that part of the component with anything we want. By default, it still works the way it used to be, but there are more options for doing so
{{text}}
Now we can use this component in many different ways. Simple, default, or custom way.
Do something a little different here
3. Use quotation marks to listen for nested attributes
You may not know this, but we can easily listen for nested values directly by using quotation marks:
Watch {'$route.query.id' () {/ /...}}
4. Know when to use v-if (and when to avoid it)
Instead of using v-if and sometimes using v-show instead, there will be 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.
If the component you are switching is expensive to render, it will be more efficient to do so.
On the other hand, 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.
5. Shorthand for a single scope slot (no template tag is required)
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.
Common way of writing:
Do not use template:
It's simple, straightforward, and amazing.
6. Conditional rendering slot
Let's take a look at how to do this, and then discuss why we want to hide the slot.
Each Vue component has a special $slots object with all your slots in it. The key of the default slot is default, and any named slot uses its name as the key.
Const $slots = {default:, icon:, button:,}
But this $slots object has only the slot that applies to the component, not each defined slot.
Take this component that defines several slots, including several named slots.
Here are some slots
If we apply only one slot to the component, then only that slot will be displayed in our $slots object.
This will be applied to the second slot. $slots = {second:}
We can use this in our components to detect which slots have been applied to the components, for example, by hiding the wrapper elements of the slots.
A wrapped slot
Now, the styled wrapper div is rendered only if we fill the slot with something.
If you don't use v-if, if you don't have a slot, you'll get an empty, unnecessary div. Depending on the style of div, this may disrupt our layout and make the interface look strange.
So why do we want to be able to render slots conditionally?
There are three main reasons for using conditional slots:
When using encapsulated div to add default styles
The slot is empty.
If we combine the default content with nested slots
For example, when we add a default style, we add a div around the slot:
This is a pretty great component, amirite? Click me!
However, if the parent component does not apply the content to the slot, we will eventually render an empty div on the page.
This is a pretty great component, amirite? Click me!
The solution is, as mentioned above, to judge multiple conditions, and that's all.
7. How to listen for changes in a slot
Sometimes we need to know when the contents of the slot have changed.
Unfortunately, Vue has no built-in way for us to detect this.
However, my friend Austin came up with a very clean way to use MutationObserver to do this.
The MutationObserver interface provides the ability to monitor changes made to the DOM tree. It is designed as a replacement for the old Mutation Events function, which is part of the DOM3 Events specification.
Export default {mounted () {/ / call `update` const observer = new MutationObserver (this.update) when there is a change; / / listen for changes in this component observer.observe (this.$el, {childList: true, subtree: true});}}
This involves a lot of content, later will be a separate article to say, remember to pay attention to the official account of dishwashing wisdom!
8. Mix local and global style
Typically, when dealing with styles, we want them to be divided into a separate component.
.component {background: green;}
However, if necessary, you can also add a non-scoped style block to add a global style
/ * Global * / .component p {margin-bottom: 16px;} / * valid within this component * / .component {background: green;}
Be careful, however, that global styles are dangerous and difficult to track. But sometimes they are the perfect escape hatch, just what you need.
9. Rewrite the style of subcomponents-- the correct approach
Scoped CSS is great at keeping content clean and doesn't introduce styles into other components of the application.
But sometimes you need to override the style of a subcomponent and jump out of the scope.
Vue has a deep selector:
.my-component > .child-component {font-size: 24px;}
Note: if you use a CSS preprocessor like SCSS, you may need to use / deep/ instead.
10. Create magic with context-aware components
* * context-aware components (context-aware) * * are "magical" and they automatically adapt to what's going on around them, dealing with edge situations, state sharing, and so on.
There are three main types of context-aware, but Configuration is the one I am most interested in.
1) State sharing
When you decompose a large component into multiple small components, they often still need to share state.
We can do this work "behind the scenes" instead of pushing it on to the user.
We generally break down Dropdown components into Select and Option components, which gives us more flexibility. But for ease of use, Select and Option components share selected state with each other.
Mustard Ketchup Relish
2) Configuration
Sometimes, the behavior of a component needs to change according to the rest of the application. This is usually done to automatically handle edge situations, which would otherwise be annoying.
A Popup or Tooltip should be repositioned so that it does not overflow the page. However, if the component is within a modal, it should be relocated so that it does not overflow modal.
This can be done automatically if Tooltip knows it is in a mode.
3) style
A CSS for context-aware is created, applying different styles depending on the parent or sibling element.
Font-weight {color: black; font-size: 24px; font-weight: bold;}. Statistic + .customers {margin-left: 10px;}
The CSS variable takes us a step further, allowing us to set different values in different parts of a page.
11. How to create a responsive variable outside of Vue (Vue2 and 3)
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 complete const externalVariable = getValue (); const reactiveVariable = ref (externalVariable); console.log (reactiveVariable.value) completely outside the Vue component.
Use reactive instead of:
Import {reactive} from 'vue';// can complete const externalVariable = getValue () completely outside the Vue component; / / reactive works only on objects and arrays const anotherReactiveVariable = reactive (externalVariable); / / Access directlyconsole.log (anotherReactiveVariable)
If you are still using Vue2, you can use observable instead of reactive to achieve exactly the same results.
12. Deconstruction in v-for
Did you know that deconstruction can be used in-vfor?
{{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 property.
# {{index + 1}. {{key}}: {{value}}
13. Cycle within a specified range
The v-for instruction allows us to traverse the array, but it also allows us to traverse a range
Item # {{n}}
Render the result:
Item # 1Item # 2Item # 3Item # 4Item # 5
When we use v-for with ranges, it starts at 1 and ends with the number we specify.
14. Monitor anything in your components
Export default {computed: {someComputedProperty () {/ / Update the computed prop},}, watch: {someComputedProperty () {/ / Do something when the computed prop is updated}
We can monitor:
Calculation attribute
Props
Nested valu
If you use a combined API, any value can be monitored as long as it is a ref or reactive object.
15. Steal prop types
I copy prop types from a child component just to use them in a parent component. But I've found that stealing these prop types is much better than just copying them.
For example, we use an Icon component in this component.
{{heading}}
In order for it to work, we need to add the correct prop type and copy it from the ``Icon` component.
Import Icon from'. / Icon' Export default {components: {Icon}, props: {iconType: {type: String, required: true,}, iconSize: {type: String, default: 'medium', validator: size = > [' small', 'medium',' large', 'xMuthlarge'] .colors (size), iconColour: {type: String Default: 'black',}, heading: {type: String, required: true,}
How painful it is.
When the prop type of the Icon 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 Icon component.
So, that's why we steal the prop type of the component:
Import Icon from'. / Icon';export default {components: {Icon}, props: {... Icon.props, heading: {type: String, required: true,}
It doesn't have to be complicated.
Except in our example, we add icon to the beginning of each prop name. So we have to do some extra work to achieve this.
Import Icon from'. / Icon';const iconProps = {}; Object.entries (Icon.props). ForEach ((key, val) = > {iconProps [`icon$ {key.toUpperCase ()} `] = val;}); export default {components: {Icon}, props: {... iconProps, heading: {type: String, required: true,}
Now, if the prop type in the Icon component is modified, our component will remain up to date.
But what if a prop type is added or removed from the Icon component? To deal with these situations, we can use v-bind and a computational prop to stay dynamic.
16. Detect clicks outside (or inside) the element
Sometimes I need to check whether a click occurs inside or outside of a particular element el. This is the method I usually use.
Window.addEventListener ('mousedown', e = > {/ / get the clicked element const clickedEl = e.target; if (el.contains (clickedEl)) {/ / clicked} else {/ / outside "el" in "el"})
17. Recursive slots
Once, I decided to see if I could just use templates to make a v-for component. In the process, I also found out how to use slots recursively.
{{list [0]}}
If you want to do this as a domain slot, you just need to make some adjustments.
{{list [0]}}
Here is how to use this component.
{{item}}
18. Component metadata
Not every bit of information added to a component is a state. Sometimes we need to add some metadata to provide more information to other components.
For example, if you are working on an analytical instrument such as Google analytics:
If you want the layout to know how many columns each widget should occupy, you can add metadata directly to the component.
Export default {name: 'LiveUsersWidget', / /? Just add it as an additional attribute: columns: 3, props: {/ /...}, data () {return {/ /...};},}; export default {name: 'LiveUsersWidget', / /? Just add it as an additional attribute: columns: 3, props: {/ /...}, data () {return {/ /...};},}
You will find that this metadata is an attribute on the component.
Import LiveUsersWidget from'. / LiveUsersWidget.vue';const {columns} = LiveUsersWidget
We can also access metadata from within the component through a special $options property.
Export default {name: 'LiveUsersWidget', columns: 3, created () {/ /? `$ options` contains all the metadata for a component console.log (`Using ${this.$options.metadata} columns`);},}
Just keep in mind that this metadata is the same for every instance of the component and is not responsive.
Other uses in this area include, but are not limited to:
Keep the version number of a single component
Custom flags used to build tools to treat components differently
Add custom functions to components in addition to calculation properties, data, watch, etc.
Other
19. Multi-file and single-file components
This is a known feature of * * SFC (single file component) * *.
You can import files like regular HTML files:
This can be very convenient if you need to share styles, files, or anything else.
20. Reusable components are not what you think.
Reusable components are not necessarily large or complex.
I often make small and short components reusable.
Because I'm not rewriting this code everywhere, it's easier to update it, and I can make sure that every OverflowMenu looks and works exactly the same-because they're the same! "
Here, we use a menu component, but add an ellipsis icon to the button that triggers it. (ellipsis) icon to trigger its opening.
It doesn't seem worthwhile to make it a reusable component because it has only a few lines. Can't we add icons every time we want to use such a menu?
But this OverflowMenu will be used dozens of times, and now if we want to update the icon or its behavior, we can do it very easily. And it's easier to use.
21. Call a method from outside the component
We can call a method from outside a component by giving it a ref.
/ / Somewhere in Parent.vuethis.$refs.child.method ()
Explain the problem again.
Sometimes "best practices" don't apply to what you're doing, and you need an escape like this.
Typically, we use props and events to communicate between components. The props is sent to the child component, and the events is sent 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. Here's the logic.
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
Instead, if we set a ref on the subcomponent, we can call the method directly:
/ / Somewhere in Parent.vuethis.$refs.child.method ()
Yes, we broke the "props down, events up" rule, we broke the package, but it was clearer and easier to understand, so it was worth it.
Sometimes, the "best" solution ends up being the worst solution.
22. Listen for arrays and objects
The trickiest part of using watcher is that sometimes it doesn't seem to trigger correctly.
Usually, this is because we try to listen on arrays or objects, but do not set deep to true
Export default {name: 'ColourChange', props: {colours: {type: Array, required: true,},}, watch: {/ / use object syntax, not just method colours: {/ / this will let Vue know to look inside the array for deep: true, handler () console.log (' The list of colours has changeable') }
An API using Vue 3 would look like this:
Watch (colours, () = > {console.log ('The list of colours has changeable');}, {deep: true,})
23. Use Vue Router for deep links
We can store the state in URL, allowing us to jump directly to a specific state on the page.
For example, you load a page that has selected a date range filter:
Someurl.com/edit?date-range=last-week
This is great for parts of an application where users may share a large number of links, and for server-rendered applications, or for communicating between two separate applications, it usually provides more information than regular links.
We can store filters, search values, whether the modal box is on or off, or scroll through the list to achieve perfect infinite paging.
Using vue-router to get query parameters works like this (this also applies to most Vue frameworks, such as Nuxt and Vuepress):
Const dateRange = this.$route.query.dateRange
To change it, we use the RouterLink component and update the query.
24. Another use of template tags
The template tag can be used anywhere in the template to better organize the code.
I like to use it to simplify v-if logic, and sometimes use v-for.
In this example, we have several elements that all use the same v-if condition.
{{title}} {{subheading}}
It's a little clumsy, and it's not obvious at first, and a bunch of these elements are shown and hidden together. This could be an even worse situation on a larger, more complex component
But we can optimize it.
We can use the template tag to group these elements and promote v-if to the template template itself.
{{title}} {{subheading}}
It seems easier to understand now, and what it is doing is clear at a glance.
25. Better ways to deal with errors (and warnings)
We can provide a custom handler for errors and warnings in Vue.
/ Vue 3const app = createApp (App); app.config.errorHandler = (err) = > {alert (err);}; / / Vue 2Vue.config.errorHandler = (err) = > {alert (err);}
Error tracking services like Bugsnag and Rollbar can hook these handlers to log errors, but you can also use them to handle errors more elegantly for a better user experience.
For example, if an error is not handled and the application does not crash directly, you can display a full error screen for the user to refresh or try something else.
In Vue3, error handlers can only handle template and watcher errors, but Vue2's error handlers can catch almost all errors. The warning handlers in both versions are valid only during the development phase.
This is the end of the content about "what are the techniques used by Vue". 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.
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.