Current location - Education and Training Encyclopedia - Graduation thesis - Some summaries on the popularization of Vue.js
Some summaries on the popularization of Vue.js
This time, I will bring you some summaries that you must know when upgrading Vue.js What are the precautions for upgrading Vue.js? The following is an actual case. Let's have a look.

The first trick: simplify the observer of complex things.

Scene restoration:

Created () {

this.fetchPostList()

},

Observation: {

searchInputValue(){

this.fetchPostList()

}

}

We get a list when we create a component and listen to the input box at the same time. It is very common to get the filtered list again every time there is a change. Is there any way to optimize it?

Mobile analysis:

First of all, in watchers, you can directly use the literal name of the function; Second, declaring immediate:true means that the component executes immediately when it is created.

Observation: {

searchInputValue:{

Handler:' fetchPostList',

Instant: correct

}

}

The second trick: once and for all component registration.

Scene restoration:

Import BaseButton from''. /baseButton '

Import BaseIcon from''. /baseIcon

Import BaseInput from''. /baseInput '

Export default value {

Component: {

Basic button,

BaseIcon,

Basic input

}

}< basic input

v-model="searchText "

@keydown.enter="search "

/& gt;

& ltBaseButton @ click = " search " & gt

& ltbase icon name = " search "/& gt;

& lt/base button & gt;

We have written a bunch of basic UI components, and then every time we need to use these components, we have to import them first, and then declare them, which is very tedious! Adhering to the principle of being lazy when you can, we must find ways to optimize!

Mobile analysis:

We need to use the artifact webpack to create our own (module) context by using the require.context () method, so as to realize the automatic dynamic requirement of components. This method requires three parameters: the folder directory to be searched, whether it should also be searched in its subdirectories, and the regular expression of matching files.

We add a file named global.js to the components folder, and dynamically package all the required basic components into this file with the help of webpack.

Import Vue from "vue"

function capitalize first letter(string){

Returns string.charAt(0). toupper case()+string . slice( 1)

}

const require component = require . context(

'.',false,/\。 vue$/

//Found a file named. Vue under the component folder.

)

requireComponent.keys()。 forEach(fileName = & gt; {

Const component config = requirecomponent (file name)

const component name = capitalize first letter(

Filename.replace (/\. \/,''). Replace (/\). \w+$/,'')

//Because the obtained file name format is:'. /baseButton.vue', here we turn around and add the tail, only keeping the real file name.

)

Vue.component (component name, component configuration. Default value || component configuration)

})

Finally, we import' components/global.js' into main.js, and then we can use these basic components anytime and anywhere without manual introduction.

The third measure: the router key, which is the bottom-up salary.

Scene restoration:

The following scene really breaks the hearts of many programmers ... First, by default, everyone uses Vue-router to realize routing control.

Suppose we are writing a blog site, and the demand is to jump from /post-page/a to /post-page/b, and then we are surprised to find that the data has not been updated after the page jump? ! The reason is that vue-router "intelligently" found that this is the same component, and then it decided to reuse this component, so the method you wrote in the created function was never executed. The usual solution is to monitor the change of $route to initialize the data, as follows:

data() {

Return {

Load: false,

Error: null,

Post: empty

}

},

Observation: {

$route': {

Handler:' resetData',

Instant: correct

}

},

Method: {

resetData() {

this.loading = false

this.error = null

this.post = null

this.getPost(this。 $route.params.id)

},

getPost(id){

}

}

Bug solved, but is it too elegant to write like this every time? Adhering to the principle of laziness, we want the code to write like this:

data() {

Return {

Load: false,

Error: null,

Post: empty

}

},

Created () {

this.getPost(this。 $route.params.id)

},

Method () {

getPost(postId) {

// ...

}

}

Mobile analysis:

How can we achieve this effect? The answer is to add a unique key to router-view, so that even public components will be recreated as long as the url changes. Although we lost the lost performance, we avoided infinite mistakes. At the same time, notice that I directly set the key to the full path of the route, killing two birds with one stone.

& ltrouter-view:key = " $ route . full path " & gt; & lt/router-view & gt;

The fourth trick: universal rendering function

Scene restoration:

Vue requires that each component has only one root element. When you have multiple root elements, vue will give you an error.

& lt template & gt

& lt Li

V-for= "route in route"

:key="route.name "

& gt

& ltrouter-link:to = " route " & gt;

{{ route.title }}

& lt/router-link & gt;

& lt/ Li>

& lt/template & gt;

Error-Component template should contain only one root element.

If you use v-if on multiple elements, use v-else-if.

Lock them up.

Mobile analysis:

Is there any way to solve it? The answer is yes, but at this time we need to use the render () function to create HTML instead of template. In fact, the advantage of using js to generate html is that it is extremely flexible and powerful, and there is no need to learn to use vue's instruction API, and its functions are limited, such as v-for.

If. (reactjs completely discards the template. )

Functionality: Really,

render(h,{ props }) {

return props . routes . map(route = & gt;

& ltli key = { route.name } & gt

& ltrouter-link to = { route } & gt;

{route.title}

& lt/router-link & gt;

& lt/ Li>

)

}

The fifth trick: advanced components that have no tricks to win.

Key point: This move is extremely powerful, please be sure to master it.

When we write a component, we usually need to pass a series of props from the parent component to the child component, and the parent component listens to a series of events of the child component emit. For example:

//Parent component

& lt basic input

:value="value "

Label= "password"

Placeholder= "Please fill in the password"

@input="handleInput "

@ focus = " handleFocus & gt

& lt/base input & gt;

//subcomponent

& lt template & gt

& lt label & gt

{{ label }}

& lt investment

:value="value "

:placeholder="placeholder "

@focus=$emit('focus ',$event)"

@input="$emit('input ',$event.target.value)"

& gt

& lt/label & gt;

& lt/template & gt;

There are the following optimization points:

1. Every attribute passed from the parent component to the child component must be explicitly declared in the attribute of the child component before it can be used. In this way, our subcomponents need to declare many props every time.

Dom native properties like placeholer can actually be passed directly from the parent to the child without declaration. The method is as follows:

& lt investment

:value="value "

v-bind="$attrs "

@input="$emit('input ',$event.target.value)"

& gt

$attrs contains attribute bindings (except classes and styles) that are not recognized (and obtained) as correct in the parent scope. When a component does not declare any

Prop, which will contain all the bindings of the parent scope, and internal components can be passed in through v-bind="$attrs "-very useful when creating higher-level components.

2. Note that the subcomponent's @focus=$emit('focus', $event) "actually didn't do anything, just sent the event back to the parent component, which is actually similar to the above, so I don't need to explicitly declare it:

& lt investment

:value="value "

v-bind="$attrs "

v-on="listeners "

& gt

Calculated value: {

listeners() {

Return {

... this. $ Audience,

Input: event =>

This. $emit('input ',event.target.value)

}

}

}

$listeners contains v-on event listeners in the parent scope (no. Native decorator). It can pass in internal components through v-on="$listeners "-very useful when creating higher-level components.

3. It should be noted that because our input is not the root node of the component BaseInput, the parent scope will not be recognized as props by default.

The function binding of will "fall back" and be used as normal HTML.

This attribute is applied to the root element of the child part. So we need to set inheritAttrs:false, and these default behaviors will be removed, so that the optimization of the above two points can be successful.

I believe you have mastered the method after reading this case. For more exciting, please pay attention to other related articles on Gxl!

Recommended reading:

Vue's beginner's course

How to package Vue projects by environment?