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 the new features in the higher version of Vue

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

Share

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

This article mainly introduces "how to use the new features in the high version of Vue". In the daily operation, I believe that many people have doubts about how to use the new features in the high version of Vue. The editor consulted all kinds of materials and sorted out simple and easy-to-use methods of operation. I hope it will be helpful to answer the doubts about "how to use the new features in the high version of Vue". Next, please follow the editor to study!

1. Depth action selector (>)

Strictly speaking, this should be a function of vue-loader. "vue-loader": "^ 12.2.0"

In the project development, if the business is more complex, especially the middle platform or B-end functional pages will inevitably use the third-party component library, the product will sometimes want to customize these components in UI. If these components use scoped CSS, it will be troublesome for the parent component to customize the style of the third-party component.

The depth action selector (> operator) can help you.

If you want a selector in the scoped style to work "deeper", such as affecting subcomponents, you can use > to operate export default {name: 'child', data () {return {}}. Child-title {font-size: 12px;}

In the above child component, the scope CSS of .child-title sets the font size to 12px, and now you want to customize it to the size 20px in the parent component, and the color is red.

Import Child from'. / child'; export default {name: 'parent', components: {Child}, data () {return {}}. Parent-custom > > .child-title {font-size:20px; color: red;}

It works well. But don't be happy too early, notice that the above style uses pure css syntax, and if you use less syntax, you may receive an error message from webpack.

.parent-custom {> .child-title {font-size:20px; color: red } ERROR in. / ~ / CssMuil loaderloader.According to the following: {"vue": true, "id": "data-v-960c5412", "scoped": false, "hasInlineConfig": false}. / / postcssMurloaderloaderloaderloader.CPUTUBUBULITE loader.Placement CPUBUBULITE loader.CPUENTULYERS index.According to: Unrecognised input @ / src/components/parent.vue Column 6) near lines: .parent-custom {> > .child-title {font-size:20px

The above error message is actually less syntax unrecognized >. (the > > operator is proposed on less's github issue, but this is a problem with v2.7.3 used in this article.)

The solution is to use less escape (scaping) and variable interpolation (Variable Interpolation)

@ deep: ~'>'; .parent-custom {@ {deep} .child-title {font-size:20px; color: red;}}

For other css preprocessors, because they are not used much, they will not comment casually and copy the documents.

Some preprocessors like Sass fail to parse > correctly. In this case you can use the / deep/ operator instead-this is an alias for >, and it also works.

Component configuration item inheritAttrs, component instance properties $attrs and $listeners

2.4.0 New

Component configuration item inheritAttrs

We all know that if three prop are passed when using the subcomponent, and the props option of the subcomponent only declares an and b, then c will be displayed as a html custom attribute on the root element of the subcomponent after rendering.

If you don't want to, you can set the subcomponent's configuration item inheritAttrs:false, and the root element will be much cleaner.

Export default {name: 'child', props: [' axiajiaozhongb'], inheritAttrs:false}

Component instance properties $attrs and $listeners

Let's see what the vm.$attrs document says.

Vm.$attrs

Type: {[key: string]: string}

Read-only

Contains feature bindings in the parent scope that are not recognized (and acquired) as prop (except class and style). When a component does not declare any prop, it contains bindings for all parent scopes (except class and style), and internal components can be passed in via vClure bind = "$attrs"-- useful when creating high-level components.

To sum up, there are two points:

Vm.$attrs is a built-in property of the component, and the value is the prop of all prop passed by the parent component that is not declared by the component (except class and style).

Or take the previous child component as an example

/ / parent.vue / / child.vue export default {name: 'child', props: [' axiaqiaojia'], inheritAttrs:false, mounted () {/ / console output: / / child:$attrs: {c: "c"} console.log ('child:$attrs:',this.$attrs);}}

Components can further pass values to their own subcomponents by using vmurbind = "$attrs" on their own subcomponents. That is, the subcomponent treats the value of $attrs as an incoming prop, while obeying the rules of the * * point.

/ / parent.vue / / child.vue export default {name: 'child', props: [' axiajiaojia'], inheritAttrs:false} / / grandchild.vue export default {name: 'grandchild', props: [], / / props: [' c'], inheritAttrs:false Mounted () {/ / console output: / / grandchild:$attrs: {d: "d", c: "c"} console.log ('grandchild:$attrs:',this.$attrs) / / if props: ['c'] / / console output: / / grandchild:$attrs: {d: "d"}},}

Vm.$listeners

Type: {[key: string]: Function | Array}

Read-only

Contains v-on event listeners in the parent scope (without the. Native modifier). It can pass in internal components via vMuon = "$listeners"-- useful when creating higher-level components

To sum up, there are two points:

Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community

Vm.$listeners is a built-in property of a component whose value is the v-on event listener of the parent component (without the .native modifier).

Components can further pass values to their own subcomponents by using vmuron = "$listeners" on their own subcomponents. If the subcomponent is already bound to a listener with the same name in $listener, the two listener functions will be executed successively in a bubbling manner.

/ / parent.vue export default {name: 'parent', components: {Child}, methods: {onParentUpdate () {console.log (' parent.vue:onParentUpdate')} / / child.vue export default {name: 'child' Components: {GrandChild}, methods: {onChildUpdate () {console.log ('child.vue:onChildUpdate')} / / grandchild.vue export default {name:' grandchild' Mounted () {/ / console output: / / grandchild:$listeners: {update: output} console.log ('grandchild:$listeners:',this.$listeners) / / console output: / / child.vue:onChildUpdate / / parent.vue:onParentUpdate this.$listeners.update ();}}

3. Component options provide/inject

2.2.0 New

If you enumerate the communication methods between Vue components, it is generally said that through prop, custom events, event bus, and Vuex. Provide/inject provides another approach.

This pair of options need to be used together to allow an ancestral component to inject a dependency into all its descendants, no matter how deep the component level is, and will remain in effect for as long as the upstream and downstream relationship is established.

If you are familiar with React, this is similar to the contextual feature (context) of React.

It is important to note, however, that direct use in applications is not recommended in the documentation.

Provide and inject mainly provide use cases for high-level plug-in / component libraries. It is not recommended to be used directly in application code.

/ / parent.vue export default {name: 'parent', provide: {data:' I am parent.vue'}, components: {Child}} / / child.vue export default {name: 'child' Components: {GrandChild}} / / grandchild.vue export default {name: 'grandchild', inject: [' data'], mounted () {/ / console output: / / grandchild:inject: I am parent.vue console.log ('grandchild:inject:',this.data) }}

The provide option should be an object or a function that returns an object. This object contains properties that can be injected into its descendants.

The inject option should be an array of strings or an object whose key represents the name of the local binding, and value is the key to be valued in provide.

When the inject option is an object at 2.5.0 +, you can also specify from to represent the source property, and default to specify the default value (use a factory method if it is a non-original value).

Const Child = {inject: {foo: {from: 'bar', default:' foo' / / default: () = > [1,2,3]}

Fourth, scope slot slot-scope

2.1.0 New

In 2.5.0 no longer limited to template elements, but can be used on any element or component in the slot.

The documentation for scope slots is detailed. Let's give an example to show the application scenario.

You can see that the list page and the edit page have the same display of data, and the difference is that there are different processing logic for data on different pages. The same data display can be extracted into a component, while different places can be realized with the help of scope slots.

/ / data-show.vue {{item.title}} / / list.vue

List page

✓ x / / edit.vue

Edit page

View changes

Error trapping of Vue

Global configuration errorHandler

Since 2.2.0, this hook will also catch errors in component lifecycle hooks.

Since 2.4.0, this hook will also catch errors inside the Vue custom event handler.

For more detailed instructions, please see the documentation errorHandler.

Lifecycle hook errorCaptured

2.5.0+ New

For more detailed instructions, please see the documentation errorCaptured.

If you are familiar with React, you will find that it is very similar to the concept of error boundary (Error Boundaries), and in fact it is used in this way.

A typical example is given in the document Error Handling with errorCaptured Hook

Vue.component ('ErrorBoundary', {data: () = > ({error: null}), errorCaptured (err, vm, info) {this.error = `${err.stack}\ n\ nfound in ${info} of implement` return false}, render (h) {if (this.error) {return h (' pre', {style: {color: 'red'}}) This.error) / / ignoring edge cases for the sake of demonstration return this.$slots.default [0]}})

It should be emphasized that errorCaptured does not catch its own errors and asynchronous errors (such as errors caused by network requests, mouse events, etc.).

At this point, the study on "how to use the new features in the high version of Vue" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

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