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 does Vue restrict prop to a type list

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

Share

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

In this article Xiaobian for you to introduce in detail "Vue how to limit prop to the type list", the content is detailed, the steps are clear, the details are handled properly, I hope this "Vue how to limit prop to type list" article can help you solve your doubts, the following follows the editor's ideas slowly in depth, together to learn new knowledge.

1. Restrict prop to type list

By using the validator option in the prop definition, you can limit the prop to a specific set of values:

Export default {name: 'Image', props: {src: {type: String,}, style: {type: String, validator: s = > [' square', 'rounded'] .requests (s)}

This validator function accepts a prop and returns either true or false. You can also use it when you need more options than Boolean values allow. Button types or alert types (information, success, hazard, warning) are some of the more common uses. [related recommendation: vuejs video tutorial]

two。 Default content and extension point

Slot in Vue can have default content, and you can make components that are easier to use:

Click me

Basically you can take any part of the component, wrap it in a slot, and then you can overwrite that part of the component with anything you want. By default, it still works as usual, but there are more options:

{{text}}

Now you can use this component in many different ways. Simple default method or your own custom way:

Do something different here. Use quotation marks to observe nested values

You may not know this: you can easily view nested values directly by using quotation marks:

Watch {'$route.query.id' () {/ /...}}

This is very useful for dealing with deeply nested objects

4. Know when to use v-if (and when to avoid it)

Sometimes without v-if, it is more efficient to use v-show:

When v-if is turned on and off, it completely creates and destroys elements. V-show differs by creating an element and leaving it there, hiding it by setting its style to display: none.

If the components you need to switch are more expensive to render, this will be more efficient. On the other hand, if you don't need to use that component immediately, you can use v-if so that it skips rendering it and loads the page faster.

5. Shorthand for single scope slot (no template tags are required! )

Scoped slot is interesting, but you also have to use a lot of template tags in order to use them.

However, there is a shorthand that allows us to get rid of it, but only if we use a single scope slot.

You don't have to write like this:

We can write like this:

This is simpler and more direct.

6. Render slot conditionally

Each Vue component has a special $slots object that contains all the slot. The default slot has default keys, and named slot uses their names as keys:

Const $slots = {default:, icon:, button:,}

But this $slots object only applies to the slot of the component, not each defined slot.

Take this component that defines several slot as an example, including several named slot:

Here are some slots

If we apply only one slot to the component, only that slot will appear in our $slots object:

This will apply to the second slot $slots = {second:}

We can use it in our components to detect which slot has been applied to the component, for example, by hiding the wrapper elements of the slot:

Slot of a package

Now div, the wrapper that applies the style only appears when we actually populate the slot with something.

If we don't use slot if we don't have a div, we'll end up getting an empty and unnecessary one. Depending on the style of the div, this can mess up our layout and make things look strange.

Why do we want to be able to render slot conditionally?

There are three main reasons for using conditional slot:

When using wrapper div to add default styles

Slot is empty

When we combine default content with nested slot

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 one on the page div:

This is a great component Click me!

V-if adds it to the wrapper div to solve the problem. What is not applied to slot? Like this:

This is a great component Click meteor7. How to observe the change of slot

Sometimes we need to know when the content in the slot has changed:

Unfortunately, Vue doesn't have a built-in way to detect this, and it's a very simple way to use the mutation viewer:

Export default {mounted () {/ / call `update` const observer = new MutationObserver (this.update) when things change; / / observe the changes in this component observer.observe (this.$el, {childList: true, subtree: true});}}; 8. Mix local and global styles

Usually when using styles, we want them to be limited to a single component:

.component {background: green;}

You can also add a non-scoped style block to add global styles if you need:

/ * Global application * / .component p {margin-bottom: 16px;} / * scope is limited to this particular component * / .component {background: green;} 9. Overriding the style of subcomponents-the right approach

Scoped CSS is easier to keep tidy and doesn't accidentally infiltrate styles into other parts of the application. But sometimes you need to override the style of the subcomponents and break out of the scope. Vue has a deep selector specifically for this:

/ * override the CSS of the subcomponent while keeping the style range * / .my-component > > .child-component {font-size: 24px;}

Note: if you are using a CSS preprocessor such as SCSS, you may need to use / deep/ instead.

10. Create magic with context-aware components

Context-aware components are "magical"-they can automatically adapt to what's going on around them, handle edge situations, state sharing, and so on. There are three main types of context-aware components, but I think configuration is one of the most interesting.

1. State sharing

When you decompose a large component into multiple small components, they usually still need to share state. You can do this "behind the scenes" instead of pushing the work on the people who use the components.

You can decompose a Dropdown component into Select and Option components to provide more flexibility. But to make it easier to use, Select and Option components share selected state with each other:

Mustard Ketchup Relish 2. Configuration

Sometimes you need to change the behavior of components depending on the rest of the application. This is usually done to automatically handle edge situations, otherwise it will be troublesome. Popup or Tooltip should reposition itself so that it does not overflow the page. However, if the component is inside the modal, it should relocate itself to avoid overflowing the modal. This can be done automatically if Tooltip knows when it is in mode.

3. Modeling

When you create a context-aware CSS, apply different styles depending on what happens in the parent or sibling element.

Font-weight {color: black; font-size: 24px; font-weight: bold;} / * do some separation between statistics adjacent to each other * / .statistic + .statistics {margin-left: 10px;}

Variables in CSS let us go a step further and allow us to set different values in different parts of the page.

11. How do I make variables created outside of Vue responsive?

If you get a variable from outside of Vue, it's nice to be able to make it responsive. This way you can use it in computational props, observers, and anywhere else, and it works just like any other state in Vue.

When you are using options API, you just need to put it in the section of the data component:

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

When you use combined API in Vue 3, you can use ref or reactive like this:

Import {ref} from 'vue';// can complete const externalVariable = getValue (); const reactiveVariable = ref (externalVariable) completely outside the Vue component; / / access console.log (reactiveVariable.value) using .value

Use reactive instead of:

Import {reactive} from 'vue';// can complete const externalVariable = getValue () completely outside the Vue component; / / Reactive is only applicable to objects and arrays const anotherReactiveVariable = reactive (externalVariable); / / Direct access to console.log (anotherReactiveVariable)

If you are still using Vue 2 (like many of us), you can use observable instead of reactive to get exactly the same results.

twelve。 Deconstruction in v-for

Did you know that you can deconstruct in v-for?

{{name}}

As we all know, you can use tuples like this to get indexes from v-for:

{{index + 1}}-{{value}}

When using objects, you can also catch key:

{{key}}: {{value}}

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

# {{index + 1}. {{key}}: {{value}} 13. Cycle through a range in Vue

The v-for directive allows us to traverse an array, but it also allows us to traverse a range:

Project # {{n}}

Display effect:

Item # 1

Item # 2

Item # 3

Item # 4

Item # 5

When we use the v-for range, it starts at 1 and ends with the number we specify.

14. Observe anything in the component

Any response in your component can be observed:

Export default {computed: {someComputedProperty () {/ / update computing props},}, watch: {someComputedProperty () {/ / do something} when the calculated prop is updated

You can read:

Computational props

Props

Nested valu

If you use a composite API, you can monitor any value as long as it is a ref or reactive object.

15. Type of props stolen

Copy prop types from child components just to use them in the parent component. But stealing these prop types is much better than just copying them.

For example, we Icon uses a component in this component:

{{heading}}

To make it 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,}

When the prop type of the Icon component is updated, you are sure you will forget to go back to the component and update them. Over time, as the prop type of the component begins to deviate from the prop type in the component, an error Icon will be introduced.

So that's why we steal them:

Import Icon from'. / Icon';export default {components: {Icon}, props: {... Icon.props, heading: {type: String, required: true,}

Except in our example, we added "icon" at the beginning of each prop name. So we have to do some extra work to achieve this:

Import Icon from'. / Icon';const iconProps = {}; / / Do some processing beforehandObject.entries (Icon.props). ForEach ((key, val) = > {iconProps [`icon$ {key [0] .toUpperCase ()} ${key.substring (1)} `] = 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 cover these situations, we can use v-bind computing props to stay dynamic.

16. Detect clicks outside (or inside) the element

Sometimes we need to check whether the click occurs inside or outside the el of a particular element. This is the method we usually use:

Window.addEventListener ('mousedown', e = > {/ / get the clicked element const clickedEl = e.target; / / `el` is the element you are testing the external click on if (el.contains (clickedEl)) {/ / Click "el" inside} else {/ / Click outside `el`}); 17. Recursive slot

Can we v-for only use templates to make a component? In the process, I discovered how to use slot recursively.

This is what the component looks like:

{{list [0]}}

If you want to do this as a domain slot-why not?! -just make some adjustments:

{{list [0]}}

The following is how to use this component:

{{item}} 18. Component metadata

Not every piece of information you add to the component is status. Sometimes you need to add some metadata to provide more information for other components.

For example, if you want to build a bunch of different widgets for analysis dashboards such as Google Analytics:

If you want the layout to know how many columns each widget should occupy, you can add it directly to the component as metadata:

Export default {name: 'LiveUsersWidget', / /? Just add it as additional attributes 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

You can also access metadata from within the component through the special $options property:

Export default {name: 'LiveUsersWidget', columns: 3, created () {/ / `$ options` contains all the metadata of the component console.log (`Using ${this.$options.metadata} columns`);},}

Keep in mind that this metadata is the same for each instance of the component and is not responsive.

Other uses include, but are not limited to:

Keep the version number of each component

Custom flags used to build tools to treat components differently

Add custom functions to components that go beyond computing props, data, observers, and so on.

19. Multi-file single-file component

This is a little-known feature of SFC. You can import files just like regular HTML files:

This is convenient if you need to share styles, documents, or anything else. It is also very suitable for super-long component files that wear fingers due to scrolling.

20. Reusable components are not what you think.

Reusable components are not necessarily large or complex, and I often make small and short components reusable. Because I'm not going to rewrite this code everywhere, it's much easier to update it, and I can make sure that every OverflowMenu looks exactly the same as it works-- because they're the same!

Here we used a Menu component, but added a "..." (ellipsis) icon to the button that triggered it to open. It may not be worth using it to make reusable components, because it has only a few lines. Can't we just add icons every time we want to use Menu? But this OverflowMenu will be used dozens of times, and now if we want to update the icon or its behavior, we can easily do it. And it's much easier to use!

21. Call a method from outside the component

You can call the method ref from outside the component by giving it:

/ / somewhere in Parent.vue this.$refs.child.method ()

Typically, we use props and events to communicate between components. The prop is sent to the child component and the event is sent back to the parent component.

But sometimes you may encounter situations where you need the parent component to trigger a method in the child component. This is the only place where passing props down doesn't work. You can pass a Boolean value down and have the subcomponent monitor it:

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

This works fine, but only for the first call. If you need to trigger this operation multiple times, you must clean up and reset the state. Then the logic looks like this:

The Parent component passes true to triggerprop

The Watch is triggered and the Child component invokes the method

The Child component issues an event telling the Parent component that the method has been triggered successfully

The Parent component resets trigger back to false, so we can do this again

Ah.

Conversely, if we set ref on a subcomponent, we can call this method directly:

/ / somewhere in Parent.vue this.$refs.child.method ()

We broke the "props down, events up" rule and broke the package, but it's clearer and easier to understand. It's worth it!

Sometimes, the "best" solution ends up being the worst solution.

twenty-two。 Observe arrays and objects

The trickiest part of using the observer is that sometimes it doesn't seem to trigger correctly. It's usually because you're trying to view an array or an object, but you don't set deep to true:

Export default {name: 'ColourChange', props: {colours: {type: Array, required: true,},}, watch: {/ / use object syntax instead of just method colours: {/ / this will let Vue know to look inside the array deep: true / / We must move our method to the handler field handler () console.log ('color list has changed!') ;}

Reactive API with Vue 3 looks like this:

Watch (colours, () = > {console.log ('Color list changed!') ;}, {deep: true,})

If you want more information, you can refer to the documentation of Vue 3 and Vue 2.

23. Deep link with Vue Router

You can store (some) states in URL, allowing you to jump directly to a specific state on the page.

For example, you can load a page with a selected date range filter:

Someurl.com/edit?date-range=last-week

This is useful for applications where users may share a large number of links, applications rendered by the server, or passing more information between two separate applications than regular links typically provide.

You can store filters, search values, whether the mode is on or off, or where we scroll to the list-perfect for infinite paging.

Use vue-router to get the query (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 within the template to better organize the code.

I like to use it to simplify v-if logic, and sometimes so does v-for.

In this example, we have several elements that all use the same v-if condition:\

{{title}} {{subheading}}

It's a little clumsy, it's not obvious at first, a bunch of these elements are shown and hidden together. This could be a worse situation on larger, more complex components!

But we can solve this problem.

We can use the template tag to group these elements and promote them v-if to the template tag itself:\

{{title}} {{subheading}} 25. A better way to deal with errors (and warnings)

You can provide custom handlers 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 such as Bugsnag and Rollbar are hooked into these handlers to log errors, but you can also use them to handle errors more elegantly for a better user experience.

For example, if the error is not handled, the application not only crashes, but can also display a full-page error screen and let the user refresh or try something else.

In Vue 3, error handlers are only available for templates and observers, but Vue 2 error handlers can capture almost everything. The warning handlers in both versions are for development only.

After reading this, the article "how Vue restricts prop to a type list" has been introduced. If you want to master the knowledge points of this article, you still need to practice and use it yourself. If you want to know more about related articles, welcome to follow 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: 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