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 practical skills does vue have?

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

Share

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

This article mainly explains "what are the practical skills of vue". Friends who are interested may wish to have a look. The method introduced in this paper is simple, fast and practical. Let's let the editor take you to learn what practical skills vue has.

The life cycle of the listening component

For example, there are parent component Parent and child component Child. If the parent component listens to the mounted mounted by the child component, do some logical processing. The general way to write it may be as follows:

/ / Parent.vue / / Child.vue mounted () {this.$emit ("mounted");}

In addition, there is a very simple way in which child components do not need any processing, but only need to listen through @ hook when the parent component references. The code is as follows:

Of course, you can listen not only to mounted, but also to other lifecycle events, such as created,updated.

Initial immediate execution of watch

Observe and respond to data changes on the Vue instance. Similar to the monitoring callback of some data, a callback is performed for subsequent operations whenever the monitored data changes.

But when watch a variable, initialization will not be executed, as in the following example, you need to call it manually when created.

Created () {this.getList ();}, watch: {keyWord: 'getList',}

The above method can be used, but it is troublesome. We can add the immediate attribute so that it will be triggered automatically during initialization (there is no need to write created to call it), and then the above code can be simplified to:

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

Watch has three parameters:

Handler: its value is a callback function. That is, the function that should be executed when a change is heard

Deep: its value is true or false; to confirm whether to listen in depth.

Immediate: the value is true or false, which confirms whether the function of handler is executed with the current initial value

Routing parameter change component is not updated

The routing parameters change when the page of the same path jumps, but the component has no corresponding update.

Reason: the main reason is that the acquisition parameters are written in the created or mounted routing hook function, and this life cycle will not be re-executed when the routing parameters change.

Solution 1:watch snooping rout

Watch: {/ / method 1 / / listen for route changes'$route' (to, from) {if (to.query.id! = = from.query.id) {this.id = to.query.id; this.init () / / reload data}} / / method 2 sets the handling function watch: {'$route': {handler: 'init', immediate: true}} when the path changes

Solution 2: to achieve this effect, you can add a different key to the router-view, so that even if it is a common component, as long as the url changes, the component will be recreated.

Routing lazy loading

In the Vue project, there are three ways to implement route on-demand loading (route lazy loading):

/ / 1. Vue Asynchronous component Technology: {path:'/ home', name: 'Home', component: resolve = > reqire ([' path path'], resolve)} / / 2, import () const Home = () = > import ('path path') / / 3, require.ensure () {path:'/ home', name: 'Home' provided by webpack Component: r = > require.ensure ([], () = > r (require ('path path')), 'demo')}

Require.context ()

Require.context (directory,useSubdirectories,regExp)

Directory: indicates the directory to be retrieved

UseSubdirectories: whether to retrieve subdirectories

RegExp: the regular expression that matches the file, usually the file name

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}

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

Recursive component

Recursive component: the component can call itself recursively within its template, as long as you set the name component to the component.

It is important to note, however, that a condition must be given to limit the quantity, or an error will be thrown: max stack size exceeded

Component recursion is used to develop some independent components with unknown hierarchical relationships. For example: cascade selector and tree control

{{index}} export default {/ / name must be defined before the component can recursively call name: 'tree', data () {return {}}, / / receive the externally passed value props: {item: {type:Array, default: () = > []}

Clear timer or event listener

Because some pages in the project will inevitably encounter the need for timers or event monitoring. However, when leaving the current page, if the timer is not cleared in a timely and reasonable manner, it will cause business logic confusion or even application jam. At this time, you need to clear the timer event monitoring, that is, in the lifecycle function of the page unloading (closing), clear the timer.

Methods: {resizeFun () {this.tableHeight = window.innerHeight-document.getElementById ('table') .offsetTop-128}, setTimer () {this.timer = setInterval (() = > {})}, clearTimer () {/ / clear timer clearInterval (this.timer) this.timer = null}}, mounted () {this.setTimer () window.addEventListener (' resize', this.resizeFun)} BeforeDestroy () {window.removeEventListener ('resize', this.resizeFun) this.clearTimer ()}

Custom path alias

We can also add our own path aliases to the underlying configuration file

Resolve: {extensions: ['.js', '.vue', '.json'], alias: {'vue$':' vue/dist/vue.esm.js','@': resolve ('src'),' assets': resolve ('src/assets')}

Then when we import the component, we can write like this:

/ / import YourComponent from'/ src/assets/YourComponent' import YourComponent from 'assets/YourComponent'

This not only solves the trouble of too long path, but also solves the trouble of relative path.

Dynamically change the style of dom

Reason: because we append scoped to all the styles in the .vue file. This will take effect for the style in the template dom, but the final style after it takes effect is not the style name we wrote, but the encoded one. For example:

Dom .box {background: red;} .box {background: red;}

Vue translates the code as follows, so the dom structure style we stitched together in js will not take effect.

.box [data-v-11c6864c] {background:red;} dom

Solution: write the style you want to change in a non-scoped style tag.

Long list performance optimization

We should all know that vue will hijack data through object.defineProperty to achieve view response to data changes, but sometimes our components are pure data display, there will be no change, we do not need vue to hijack our data, in the case of a large number of data display, this can significantly reduce the initialization time of components.

So, we can use the object.freeze method to freeze an object, once the object is frozen, vue will not hijack the data.

Export default {data: () = > ({list: []}), async created () {const list = await axios.get ('xxxx') this.list = Object.freeze (list)}, methods: {/ / nothing done here can change the value of list}}

In addition, it is important to note that the value of list is only frozen, and references will not be frozen. When we need reactive data, we can re-assign values to list.

Content distribution (slot)

Slot slot, which is also a HTML template of the component, is determined by the parent component whether the template is displayed or not, and how to display it. In fact, the two core questions of a slot are pointed out here, that is, whether or not to display and how to display.

Default slot

Also known as a single slot, anonymous slot, this kind of slot has no specific name, a component can only have one such slot.

Parent Container menu 1 Child component

Named slot

Anonymous slots have no name attribute, so they are called anonymous slots. Then, with the name attribute added to the slot, it becomes a named slot. Named slots can appear N times in a component, in different locations, and only need to be distinguished using different name attributes.

Parent Container menu up-1 menu down-1 menu-> 1 here are child components

Scope slot

A scope slot can be a default slot or a named slot, except that the scope slot can bind data to the slot tag so that its parent component can obtain the data of the child component.

This is the parent component > {{slotProps.user.name}} > this is the child component export default {data () {return {user: {name: 'Xiao Zhao'}}. So far, I believe you have a better understanding of "what practical skills vue has". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

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