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

What skills Vue developers must know

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

Share

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

This article mainly introduces "what skills must be known in Vue development". In daily operation, I believe many people have doubts about the skills that Vue development must know. 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 of "what skills Vue development must know". Next, please follow the editor to study!

1.require.context ()

1. Scenario: if multiple components need to be imported into the page, the original writing method:

Import titleCom from'@ / components/home/titleCom' import bannerCom from'@ / components/home/bannerCom' import cellCom from'@ / components/home/cellCom' components: {titleCom,bannerCom,cellCom}

two。 In this way, a lot of repetitive code is written, which can be written with require.context.

Const path = require ('path') const files = require.context (' @ / components/home', false, /\ .vue $/) const modules = {} files.keys () .forEach (key = > {const name = path.basename (key, '.vue') modules [name] = files (key). Default | | files (key)}) components:modules

This method can be used no matter how many components are introduced into the page.

3.API method

It is actually webpack's method. Vue projects are generally based on webpack, so you can use require.context (directory,useSubdirectories,regExp) to receive three parameters: directory: indicate the directory to be retrieved: useSubdirectories: whether to retrieve subdirectories regExp: regular expressions that match files, usually file names

2.watch

2.1 Common usage

1. Scenario: the initial entry of the form requires a survey to query the interface getList (), and then the query will be re-queried if input is changed.

Created () {this.getList ()}, watch: {inpVal () {this.getList ()}}

2.2 execute immediately

two。 The abbreviations of immediate and handler attributes of watch can be used directly.

Watch: {inpVal: {handler: 'getList', immediate: true}}

2.3 Deep Monitoring

3.watch 's deep attribute, deep snooping, that is, listening for complex data types

Watch: {inpValObj: {handler (newVal,oldVal) {console.log (newVal) console.log (oldVal)}, deep:true}}

It is found that the values of oldVal and newVal are the same.

Because they index the same object / array, Vue does not keep a copy of the value before it was modified

Therefore, although deep monitoring can listen to the changes of the object, it cannot listen to the changes of the properties in the specific object.

3. 14 kinds of component communication

3.1 props

This should be a very attribute, that is, the attribute passed from father to son.

The props value can be an array or an object

/ / array: it is not recommended to use props: [] / object props: {inpVal: {type:Number, / / pass in a value to define the type / / type value can be String,Number,Boolean,Array,Object,Date,Function,Symbol / / type or a custom constructor And check through instanceof to confirm that required: true, / / required default:200, / / default value, object or array default value must be obtained from a factory function such as default: () = > [] validator: (value) {/ / this value must match a return ['success',' warning', 'danger'] .indexOf (value)! =-1}

3. 2$ emit

This should also be very common. Triggering the event that the parent component binds to itself by triggering the child component is actually the way for the child to pass on the parent.

/ / parent component / / Child component this.$emit ('title', [{title:' this is title'}])

3.3 vuex

1. This is also very common. Vuex is a state manager.

two。 Is an independent plug-in, suitable for projects with a lot of data sharing, because if it is only a simple communication, it will be heavy to use.

3.API

State: define the warehouse for storing data. You can access getter through this.$store.state or mapState: get the store value, which can be regarded as the calculation attribute of store, and access mutation through this.$store.getter or mapGetters: change the store value synchronously, why it is designed to be synchronous, because mutation changes the store value directly, and vue records the operation. If it is asynchronous, the change cannot be tracked. You can call action through mapMutations: asynchronously call the function to execute mutation, and then change the store value. You can access modules: module through this.$dispatch or mapActions. If there are too many states, you can split it into modules, and finally pass through the entrance. Deconstruction introduction

3.4 attrs and listeners

2.4.0 New

These two properties are not commonly used, but advanced usage is common

1.$attrs

Scenario: if the parent and child have many values, then multiple props need to be defined in the child component

Solution: $attrs gets values that are not defined in props in the parent of the child

/ / parent component / / Child component mounted () {console.log (this.$attrs) / / {title: "this is the title", width: "80", height: "80", imgUrl: "imgUrl"}}

Correspondingly, if the subcomponent defines a props, the printed value is to weed out the defined attribute.

Props: {width: {type: String, default:''}}, mounted () {console.log (this.$attrs) / / {title: "this is the title", height: "80", imgUrl: "imgUrl"}}

2.$listeners

Scenario: the child component needs to call the method of the parent component

Solution: the method of the parent component can be passed into the internal component via vmuron = "$listeners"-- useful when creating higher-level components

/ / parent component / / Child component mounted () {console.log (this.$listeners) / / you can get the change event}

If the grandchild component wants to access the properties and call methods of the parent component, it can be passed directly level by level.

3.inheritAttrs

/ / parent component / / Child component mounted () {console.log (this.$attrs) / / {title: "this is the title", width: "80", height: "80", imgUrl: "imgUrl"}}. The default value of inheritAttrs is true,true, which means that attributes in the parent component other than props are added to the root node of the child component (description, even if set to true The child component can still get the unexpected property of props through $attr) after inheritAttrs:false, the attribute will not be displayed on the root node

3.5 provide and inject

2.2.0 New

Description:

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

And 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 always takes effect when the upstream and downstream relationship is established.

/ / parent component: provide: {/ / provide is an object that provides a property or method foo: 'this is foo', fooMethod: () = > {console.log (' parent component fooMethod is called')}}, / / child or grandchild component inject: ['foo','fooMethod'], / / array or object Injected into the child component mounted () {this.fooMethod () console.log (this.foo)} / / all child components under the parent component can take advantage of inject

Provide and inject bindings are not responsive. This is deliberately done by the authorities.

However, if you pass in a listenable object, the properties of its object are responsive because it is a reference type

/ / parent component: provide: {foo: 'this is foo'}, mounted () {this.foo=' this is the new foo'} / / child or grandchild component inject: [' foo'], mounted () {console.log (this.foo) / / is the child component printed or 'this is foo'}

3.6 parent and children

$parent: parent instance

$children: child instance

/ / parent component mounted () {console.log (this.$children) / / you can get the properties and methods of a first-level child component / / so you can directly change the data, or call the methods method} / / child component mounted () {console.log (this.$parent) / / you can get the properties and methods of parent}

Children and parent do not guarantee order, nor are they responsive

You can only get one-level parent and child components.

3.7USD refs

/ / parent component mounted () {console.log (this.$refs.home) / / you can get the instance of the child component, and you can directly manipulate data and methods}

3.8USD root

/ / parent component mounted () {console.log (this.$root) / / get the root instance, and finally all components are mounted to the root instance console.log (this.$root.$children [0]) / / get the first-level child component console.log (this.$root.$children [0]. $children [0]) / / get the second-level child components of the root instance}

3.9 .sync

It existed as a two-way binding function in vue@1.x, that is, the child component can modify the value in the parent component.

In vue@2.0, it was killed for violating the design of a single data stream.

This .sync modifier has been reintroduced in versions above vue@2.3.0+

/ / parent component / / will be extended to / / child component / / so the child component can change mounted () {this.$emit ("update:title", 'this is the new title')} through the $emit trigger update method.

3.10 v-slot

2.6.0 New

1. Slotwright copyright scope was discarded in 2.6.0, but not removed

two。 The function is to pass the template of the parent component to the child component

3. Slot classification:

a. Anonymous slot (also known as default slot): there is no name, there is only one

/ / any content of the parent component

I'm an anonymous slot.

/ / sub-component I am the default / / v-slot:default to write the feeling and the named writing is more consistent, easy to understand, but also do not have to write

b. Named slot: relatively anonymous slot component slot label with name named

/ / any content of the parent component

I'm an anonymous slot.

/ / Sub-component I am the default

c. Scope slot: the data within the child component can be obtained by the parent page (solving the problem that the data can only be passed to the child component from the parent page)

/ / parent component {{slotProps.user.firstName}} / / slotProps can be named at will / / slotProps is a collection of attribute data on the child component tag slot. All the data binduser = "user" / / child component {{user: {lastName: "Zhang", firstName: "yue"} Test: [1Jing 2Jing 3Jing 4]}}, / / {{user.lastName}} is the default data v-slot:todo when the parent page does not have (= "slotProps")

3.11 EventBus

1. Is to declare a global Vue instance variable EventBus to store all communication data and event listeners on this variable

two。 Similar to Vuex. But this approach only applies to very small projects.

3. The principle is to use on and emit and instantiate a global vue to realize data sharing.

/ / in main.js Vue.prototype.$eventBus=new Vue () / / pass value component this.$eventBus.$emit ('eventTarget',' this is the value passed from eventTarget') / / receive component this.$eventBus.$on ("eventTarget", v = > {console.log ('eventTarget',v); / / this is the value passed from eventTarget})

4. It is possible to achieve horizontal, nested components to pass values, but the corresponding event name eventTarget must be globally unique

3.12 broadcast and dispatch

Vue 1.x has these two methods, event broadcast and dispatch, but vue 2.x has been deleted

The following is the encapsulation of two methods

Function broadcast (componentName, eventName, params) {this.$children.forEach (child = > {var name = child.$options.componentName; if (name = componentName) {child.$emit.apply (child, [eventName] .concat (params));} else {broadcast.apply (child, [componentName, eventName] .concat (params);}}) } export default {methods: {dispatch (componentName, eventName, params) {var parent = this.$parent; var name = parent.$options.componentName; while (parent & & (! name | | name! = = componentName)) {parentparent = parent.$parent; if (parent) {name = parent.$options.componentName } if (parent) {parent.$emit.apply (parent, [eventName] .concat (params));}}, broadcast (componentName, eventName, params) {broadcast.call (this, componentName, eventName, params);}

3.13 routing parameters

1. Option one

/ / Route definition {path:'/ describe/:id', name: 'Describe', component: Describe} / / the page passes the parameter this.$router.push ({path: `/ describe/$ {id}`,}) / / the page gets the this.$route.params.id

two。 Option 2

/ / routing definition {path:'/ describe', name: 'Describe', omponent: Describe} / / the page passes the parameter this.$router.push ({name:' Describe', params: {id: id}}) / / the page gets the this.$route.params.id

3. Option 3

/ / Route definition {path:'/ describe', name: 'Describe', component: Describe} / / Page pass parameter this.$router.push ({path:' / describe', query: {id: id `}) / / Page to get this.$route.query.id

4. Comparison of three schemes

The second parameter will not be spliced after the route, and the page refresh parameter will be lost.

Scheme one and three parameters are spliced at the end, ugly, and expose the information.

3.14 Vue.observable

2.6.0 New

Usage: make an object responsive. It is used internally by Vue to handle objects returned by data functions.

The returned object can be used directly in rendering functions and computational properties, and will trigger corresponding updates when changes occur; it can also be used as a minimized cross-component state memory for simple scenarios.

The principle of communication is essentially to use Vue.observable to realize a simple vuex.

/ / File path-/ store/store.js import Vue from 'vue' export const store = Vue.observable ({count: 0}) export const mutations = {setCount (count) {store.count = count}} / / usage + {{count}}-import {store Mutations} from'. / store/store' / / Vue2.6 added API Observable export default {name: 'Add', computed: {count () {return store.count}}, methods: {setCount: mutations.setCount}}

4.render function

1. Scenario: some code is written in template and repeats a lot, so this time the render function works

/ / generate tags according to props / / Primary

/ / optimized version, using the render function to reduce the code repetition rate Hello world! Import Vue from 'vue' Vue.component (' child', {render (h) {const tag = ['div',' packs, 'strong',' H2,'h3), 'textarea'] [this.level-1] return h (tag, this.$slots.default)}, props: {level: {type: Number Required: true}}) export default {name: 'hehe', data () {return {level: 3}

Comparison between 2.render and template

The former is suitable for complex logic, and the latter is suitable for simple logic.

The latter belongs to declaration and rendering, and the former belongs to custom Render function.

The performance of the former is higher, while that of the latter is lower.

5. Asynchronous component

Scenario: too large a project can lead to slow loading, so it is necessary for asynchronous components to load on demand.

1. Register components asynchronously

Three methods

/ / the factory function executes the resolve callback Vue.component ('async-webpack-example', function (resolve) {/ / this special `build` syntax will tell webpack / / automatically cut your build code into multiple packages, and these packages / / will load require (['. / my-async-component'] via Ajax request) (resolve)}) / / Factory function returns Promise Vue.component ('async-webpack-example', / / this `import` function returns a `Promise` object. () = > import ('. / my-async-component')) / / Factory function returns a configured component object const AsyncComponent = () = > ({/ / the component to be loaded (which should be a `Promise` object) component: import ('. / MyComponent.vue'), / / the component used when the asynchronous component is loaded is loading: LoadingComponent, / / the component used when loading fails: error: ErrorComponent / / shows the delay time of the component when loading. The default value is 200 (milliseconds) delay: 200, / / if a timeout is provided and the component has timed out, / / the component that was used when the load failed. The default is: `Infinity` timeout: 3000})

In essence, the rendering of an asynchronous component is to perform two or more renderings, first rendering the current component as a comment node, and then re-rendering through forceRender after the component is successfully loaded. Or render as an annotation node, and then render as a loading node, after rendering as the requested completed component

two。 Demand loading of rout

Webpack

< 2.4 时 { path:'/', name:'home', components:resolve=>

The {path:'/', name:'home', components: () = > import ('@ / components/home')} import () method is proposed by es6 when require (['@ / components/home'], resolve)} webpack > 2.4.The import () method is dynamically loaded and returns a Promise object, and the parameter of the then method is the loaded module. Similar to Node.js 's require method, the main import () method is loaded asynchronously.

6. Dynamic component

Scenario: dynamic loading of components is involved when making a tab switch

But every time the component is reloaded, it consumes a lot of performance, so it works.

There is no animation in this way, and there is no hurry about this. You can use the built-in

7. Recursive component

Scenario: if you develop a tree component whose level is based on the background data, you need to use dynamic components

/ / Recursive component: the component can call itself recursively in its template, as long as you set the name component to the component. / / set so that House can be used recursively within the component template, but it should be noted that / / A condition must be given to limit the number, otherwise an error will be thrown: max stack size exceeded / / components are recursively used to develop some independent components with unknown hierarchical relationships. For example: / / cascading selector and tree control subcomponents, the current level value: {{index}} export default {/ / name must be defined Only within the component can name be called recursively: 'tree', data () {return {}}, / / receive the externally passed value props: {item: {type:Array, default: () = > []}

Recursive components must set name and end thresholds

8. Functional component

Definition: stateless, cannot be instantiated, and there is no internal lifecycle processing

Rule: in versions prior to 2.3.0, the props option was required if a functional component wanted to receive prop.

In version 2.3.0 or above, you can omit the props option, and the features on all components are automatically implicitly resolved to prop. In version 2.5.0 and above, if you use a single-file component (that is, an ordinary .vue file), you can declare directly on template that everything needed by the functional component is passed through the context parameter.

The context properties are:

1.props: an object that provides all prop

2.children: an array of VNode child nodes

3.slots: a function that returns an object containing all slots

4.scopedSlots: (2.6.0 +) an object that exposes incoming scope slots. Normal slots are also exposed as functions.

5.data: the entire data object passed to the component, passed into the component as the second parameter of createElement

6.parent: reference to the parent component

7.listeners: (2.3.0 +) an object that contains all event listeners registered by the parent component for the current component. This is an alias for data.on.

8.injections: (2.3.0 +) if the inject option is used, the object contains the properties that should be injected

{{item}}

9.components and Vue.component

Components: locally registered component

Export default {components: {home}}

Vue.component: global registration component

Vue.component ('home',home)

10.Vue.extend

Scenario: some of the vue components need to mount some elements to the elements, and extend plays a role at this time

Is a grammars that construct a component

Written as follows:

/ / create constructor var Profile = Vue.extend ({template:'

{{extendData}} the data passed in by the instance is: {{propsExtend}}

The outermost tag corresponding to', / / template must have only one tag data: function () {return {extendData: 'this is the data of the extend extension',}}, props: ['propsExtend']}) / / the constructor created can be mounted to an element, or it can be registered with components or Vue.component () to mount to an element. Parameters can be transmitted through propsData. New Profile ({propsData: {propsExtend:' I am the incoming data from the instance'}}). $mount ('# app-extend') / / register Vue.component ('Profile',Profile) through components or Vue.component ()

11.mixins

Scenario: some components have duplicate js logic, such as verifying phone verification code, parsing time, etc. Mixins can achieve this kind of blending.

The mixins value is an array

Const mixin= {created () {this.dealTime ()}, methods: {dealTime () {console.log ('this is the method in the dealTime of mixin');}} export default {mixins: [mixin]}

12.extends

The usage of extends is similar to that of mixins, except that the arguments received are simple option objects or constructors, so extends can only extend one component at a time.

Const extend= {created () {this.dealTime ()}, methods: {dealTime () {console.log ('this is the method in the dealTime of mixin');}} export default {extends:extend}

13.Vue.use ()

Scenario: when we use element, we will first import, and then Vue.use (), which is actually registering the component and triggering the install method

This is often used in component calls

Will automatically organize multiple registrations of the same plug-in.

14.install

Scenario: Vue.use () says that executing this method triggers install

Is a plug-in for developing vue, the first parameter of this method is the Vue constructor, and the second parameter is an optional option object (optional)

Var MyPlugin = {}; MyPlugin.install = function (Vue, options) {/ / 2. To add a global resource, the second parameter passes a value that defaults to the value Vue.directive corresponding to update ('click', {bind (el, binding, vnode, oldVnode) {/ / prepare for binding, add time listener console.log (' instruct my-directive 's bind to execute') }, inserted: function (el) {/ / get the bound element console.log ('instruction my-directive 's inserted is executed');}, update: function () {/ / execute the corresponding update based on the obtained new value / / console.log is also called once for the initial value ('instruction my-directive 's update is executed') }, componentUpdated: function () {console.log ('instruct my-directive 's componentUpdated to execute');}, unbind: function () {/ / do cleanup operation / / for example, the event listener console.log bound when removing bind ('instruct my-directive 's unbind to execute') / / 3. Injection component Vue.mixin ({created: function () {console.log ('created injected into the component'); console.log ('options value is', options)}}) / / 4. Add instance method Vue.prototype.$myMethod = function (methodOptions) {console.log ('instance method myMethod has been called');}} / / call MyPlugin Vue.use (MyPlugin, {someOption: true}) / / 3. Mount new Vue ({el:'# app'})

For more information, please stamp several operations of extend,mixins,extends,components,install in vue.

15. Vue.nextTick

2.1.0 New

Scenario: when the page loads, you need to let the text box get the focus.

Usage: perform a deferred callback after the end of the next DOM update cycle. Use this method immediately after modifying the data to get the updated DOM

Mounted () {/ / because the mounted phase dom has not been rendered, you need $nextTick this.$nextTick (() = > {this.$refs.inputs.focus () / / get dom through $refs and bind the focus method})}

16.Vue.directive

16.1 use

Scene: officials have given us a lot of instructions, but if we want to change the text to a specified color and define it as an instruction, we need to use Vue.directive at this time

/ / globally define Vue.directive ("change-color", function (el,binding,vnode) {el.style ["color"] = binding.value;}) / / use {{message}} export default {data () {return {color:'green'}

16.2 Life cycle

1.bind is called only once, and the instruction is called the first time it is bound to an element. This hook allows you to define an initialization action that is performed once at the binding time.

2.inserted: called when the bound element is inserted into the parent node (it can be called if the parent node exists, but not necessarily in the document)

3.update: called when the template where the element is bound and the element is updated, and regardless of whether the bound value has changed or not, ignore unnecessary template updates by comparing the bound values before and after the update

4.componentUpdate: called when the template of the bound element completes an update cycle

5.unbind: called only once, which is called when the month element is unbound.

17. Vue.filter

Scenario: the timestamp is converted to the year, month and day, which is a common method, so it can be extracted into a filter.

/ / use / / in double curly braces {{message | capitalize}} / / in `vbind` / / globally register Vue.filter ('stampToYYMMDD' (value) = > {/ / processing logic}) / / Local registration filters: {stampToYYMMDD: (value) = > {/ / processing logic}} / / multiple filters global registration / src/common/filters.js let dateServer = value = > value.replace (/ (\ d {4}) (\ d {2}) (\ d {2}) / g Export {dateServer} / src/main.js import * as custom from'. / common/filters/custom' Object.keys (custom) .forEach (key = > Vue.filter (key))

18.Vue.compile

Scenario: compile the template string in the render function. Valid only when building independently

Var res = Vue.compile ('{msg}}') new Vue ({data: {msg: 'hello'}, render: res.render, staticRenderFns: res.staticRenderFns})

19.Vue.version

Scenario: some development plug-ins need to be compatible with different vue versions, so they use Vue.version

Usage: Vue.version () can get the vue version

Var version = Number (Vue.version.split ('.') [0]) if (version = 2) {/ / Vue v2.x.x} else if (version = 1) {/ / Vue v1.x.x} else {/ / Unsupported versions of Vue}

20.Vue.set ()

Scenario: when you directly set an array item using an index or when you modify the length of an array, the data is not updated in response due to the limitation of the Object.defineprototype () method

But the problem that vue.3.x will take advantage of proxy will be solved.

Solution:

/ / using set this.$set (arr,index,item) / / using arrays push (), splice ()

21.Vue.config.keyCodes

Scene: custom key modifier alias

/ / define the key code as f2 Vue.config.keyCodes.f2 = 113

22.Vue.config.performance

Scenario: monitoring performanc

Vue.config.performance = true

Only applicable to development mode and browsers that support performance.mark API

23.Vue.config.errorHandler

1. Scene: handlers that specify components that do not catch errors during rendering and observation

two。 Rules:

Since 2.2.0, this hook will also catch errors in component lifecycle hooks. Similarly, when the hook is undefined, the caught error will be output through console.error to prevent the application from crashing from 2.4.0, this hook will also catch errors within the Vue custom event handler from 2.6.0, this hook will also catch errors thrown within the v-on DOM listener. In addition, if any overridden hook or handler returns a Promise chain (such as the async function), errors from its Promise chain will also be handled

3. Use

Vue.config.errorHandler = function (err, vm, info) {/ / handle error / / `info` is a Vue-specific error message, such as the lifecycle hook in which the error is located / / only available in 2.2.0 +}

24.Vue.config.warnHandler

2.4.0 New

1. Scenario: assign a custom handler to the runtime warning of Vue, which will only take effect in the developer environment

two。 Usage:

Vue.config.warnHandler = function (msg, vm, trace) {/ / `trace` is component inheritance tracking}

25.v-pre

Scenario: vue is a responsive system, but some static tags do not need to be compiled multiple times, which can save performance

{{this will not be compiled}} shows {{this will not be compiled}} {{msg}} even though msg is defined in data, it still shows {{msg}}.

26.v-cloak

Scene: when the network speed is slow, when using vue to bind data, the variable flicker occurs when rendering the page

Usage: this instruction remains on the element until the associated instance is compiled. When used with CSS rules such as [v-cloak] {display: none}, this directive hides uncompiled Mustache tags until the instance is ready

/ / in template

{{value.name}}

/ / [v-cloak] {display: none;} in css

This will solve the flicker, but there will be a white screen, which can be used in combination with the skeleton screen.

27.v-once

Scenario: static dom in some template has not changed, so it only needs to be rendered once, which can reduce the performance overhead.

You only need to load the tag once at this time.

The difference between v-once and v-pre:

V-once is rendered only once; v-pre is not compiled and output as is

twenty-eight。 Event modifier

.stop: prevent bubbling. Prevent: prevent the default behavior .self: only the binding element itself triggers .once: 2.1.4, but only once. Passive: 2.3.0 is added. The default behavior of the scrolling event (that is, the scrolling behavior) will be triggered immediately and cannot be used with .resolent.

twenty-nine。 Key modifier and key code

Scene: sometimes you need to monitor the behavior of the keyboard, such as pressing enter to query the interface.

/ / corresponding keyword .enter .tab .delete (capture "delete" and "backspace" keys) .esc .space .up .down .left .right

30.Vue-router

Scenario: Vue-router is an official routing plug-in

30.1 caching and animation

1. Routing uses the official component vue-router, which I believe everyone is very familiar with.

two。 Here I will describe the caching and animation of routing.

3. You can use exclude (except) or include (including), 2.1.0 addition to judge

/ / or include= "include=" / a | b / ", an and b represent the name of the component / / because some pages, such as trying data statistics, need to be refreshed in real time, so there is no need to cache / / routing label / / c to represent the name value of the component

Note: the match first checks the name option of the component itself, and if the name option is not available, matches its local registered name (the key value of the parent component components option). Anonymous components cannot be matched

4. Judging by v-if, the components will be re-rendered, but there is no need to enumerate the components name one by one

30.2 Global routing hooks

1.router.beforeEach

Router.beforeEach ((to, from, next) = > {console.log ('global frontend: beforeEach-- next needs to be called') / / this is generally used for login interception, also known as navigation hook guard if (path = ='/ login') {next () return} if (token) {next ();}})

2.router.beforeResolve (v 2.5.0 +)

Similar to beforeEach, the difference is that the parsing guard is called before the navigation is confirmed and after the guard and asynchronous routing components are parsed within all components.

That is, to call after beforeEach

3.router.afterEach

Global rear hook

Called at the end of all route jumps

These hooks do not accept next functions and do not change the navigation itself

30.3 component routing hook

1.beforeRouteEnter

Called before the corresponding route of the rendering component is confirmed. The usage and parameters are similar to router.beforeEach. Next needs to be called actively.

At this time, the component instance has not been created and cannot access this

You can access the component instance by passing a callback to next. Performs a callback when the navigation is confirmed, and takes the component instance as a parameter to the callback method

BeforeRouteEnter (to, from, next) {/ / the component instance cannot be accessed here, this = undefined next (vm = > {/ / access the component instance} through `vm`)}

2.beforeRouteUpdate (v 2.2 +)

When the current route changes and the component is reused, the instance can be accessed through this. Next needs to be called actively and cannot be called back.

3.beforeRouteLeave

It is called when the navigation leaves the corresponding route of the component, and the component instance can be accessed. The this,next needs to be called actively and cannot be called back.

30.4 route pattern

Set the mode property: hash or history

30.5 Vue.$router

This.$router.push (): jump to a different url, but this method adds a record to the history stack, and clicking back returns to the previous page this.$router.replace (): there is no record this.$router.go (n): n can be positive or negative. Positive numbers return to the previous page, similar to window.history.go (n)

30.6 Vue.$route

Represents the routing object that is currently redirected. The attributes are:

Name: route name

Path: path

Query: passing parameters to receive valu

Params: passing parameters to receive valu

FullPath: the URL after parsing, including the query parameters and the full path of hash

Matched: copy of routing record

RedirectedFrom: if there is a redirect, that is, the name of the route that is the source of the redirection

This.$route.params.id: get the parameters passed through params or /: id this.$route.query.id: get the parameters passed through query

Key of 30.7 router-view

Scenario: because Vue reuses the same components, that is, when links such as / page/1 = > / page/2 or / page?id=1 = > / page?id=2 jump, hooks such as created and mounted will not be executed

So that both the created and mounted of the component will be executed

31.Object.freeze

Scenario: a long list of data that usually does not change, but vue does the conversion between getter and setter

Usage: a new feature of ES5 that freezes an object to prevent it from being modified

Support: vue 1.0.18 + supports it. For objects frozen by freeze in data or vuex, vue will not convert getter to setter.

Note: freezing only freezes a single attribute, and the reference address can still be changed.

New Vue ({data: {/ vue will not getter the object in list, setter binding list: Object.freeze ([{value: 1}, {value: 2}])}, mounted () {/ / interface will not respond, because a single attribute is frozen this.list [0] .value = 100 / / in both of the following ways, the interface will respond this.list = [{value: 100}, {value: 200}]; this.list = Object.freeze ([{value: 100}, {value: 200}]);}})

thirty-two。 Debug template

Scenario: in the process of Vue development, you often encounter errors in JavaScript variables when rendering template templates. At this time, you may use console.log to debug.

At this point, you can mount a log function in the development environment

/ / main.js Vue.prototype.$log = window.console.log; / / component internal {{$log (info)}}

33.vue-loader Tips

33.1 preserveWhitespace

Scenario: the development of vue code usually has spaces. At this time, packaging and compression will increase the size of the package if the spaces are not removed.

Configure preserveWhitespace to reduce the size of packets

{vue: {preserveWhitespace: false}}

33.2 transformToRequire

Scenario: in the past, when writing Vue, I used to write code like this: require the picture in advance to a variable and then pass it to the component

/ / page code export default {created () {this.imgSrc = require ('. / assets/default-avatar.png')}}

Now: after configuring transformToRequire, you can configure it directly, so that vue-loader will automatically require the corresponding properties and pass them to the component.

/ / vue-cli 2.x the default configuration in vue-loader.conf.js is transformToRequire: {video: ['src',' poster'], source: 'src', img:' src', image: 'xlink:href'} / / configuration file If vue-cli2.x modifies avatar in vue-loader.conf.js: ['default-src'] / / vue-cli 3.x change the transformToRequire attribute to transformAssetUrls module.exports = {pages in vue.config.js / / vue-cli 3.x ChainWebpack: config = > {config .module .rule ('vue') .use (' vue-loader') .loader ('vue-loader') .tap (options = > {options.transformAssetUrls = {avatar:' img-src',} return options });}} / / page code can be simplified to

thirty-four。 Set an alias for the path

1. Scenario: in the development process, we often need to introduce various files, such as pictures, CSS, JS, etc. In order to avoid writing a long relative path (.. /), we can configure an alias for different directories.

2.vue-cli 2.x configuration

/ / for the resolve configuration item in webpack.base.config.js, add aliases resolve: {extensions: ['.js', '.vue', '.json'], alias: {'vue$':' vue/dist/vue.esm.js','@': resolve ('src'),}}

3.vue-cli 3.x configuration

/ / create vue.config.js var path = require ('path') function resolve (dir) {console.log (_ _ dirname) return path.join (_ _ dirname, dir)} module.exports = {chainWebpack: config = > {config.resolve.alias .set (key,value) / / key,value in the root directory, such as .set (' @ @', resolve ('src/components'))}}

35.img failed to load

Scene: sometimes the image address returned by the background may not be opened, so you should add a default picture at this time.

/ / page code

Export default {data () {return {imgUrl:''}}, methods: {handleError (e) {e.target.src=reqiure ('image path') / / of course, if the project is configured with transformToRequire, see above

36.css

36.1 Local Styl

The scoped attribute of the style tag in 1.Vue indicates that its style only works on the current module and is privatized.

two。 Rules / principles of rendering:

Add a non-repeating data attribute to the DOM node of HTML to represent uniqueness

Add a data property selector of the current component to the end of the corresponding CSS selector to privatize the style, such as: .demo [data-v-2311c06a] {}

If less or sass is introduced, it will only be set on the last element

/ / original code Vue.js scoped .demo {font-size: 16px; .content {color: red;}} / / browser rendering effect Vue.js scoped .demo [data-v-039c5b43] {font-size: 14px } .demo .content [data-v-039c5b43] {/ / .demo does not add the data attribute color: red;}

36.2 deep Properties

/ / add a / deep/ .demo {font-size: 14px;} .demo / deep/ .content {color: blue;} / / browser compiled .demo [data-v-039c5b43] {font-size: 14px;} .demo [data-v-039c5b43] .content {color: blue At this point, the study of "what skills Vue developers must know" 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