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

Example Analysis of readability of Vue Code

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 the example analysis of the readability of Vue code, which has a certain reference value. Interested friends can refer to it. I hope you will gain a lot after reading this article.

First, make good use of components to make the code more organized

Never put all the implementation code of a page in a .vue file, unless the page is very simple, the code in the .vue file will be long and smelly.

Vue provides components not only for reuse, but also for splitting code, and even making good use of components can optimize the speed of page rendering updates. This is because the components in the page are not updated when the Vue page is rendered, unless the data referenced by the props or slot of the component changes.

You can split a Vue page into components to make the code more organized by following these steps

1. Extract UI components

How do you define UI components? Personally, it is recommended to distinguish between UI components and business components according to whether server-side data is processed or not. For example, load pop-up window, double confirmation pop-up window, message prompt box, and so on belong to UI interaction.

After the UI component is extracted, the code for the UI interaction can be separated from the code for the business interaction. Remember that you cannot write business code in UI components, so that UI components cannot be reused.

To take a counterexample, add the business code to be processed after the second confirmation in the secondary confirmation pop-up window, so that the UI component will not be reused. We can imitate the call of the second confirmation pop-up window in ElementUI to implement a second confirmation pop-up window component.

This.$confirm (message, title, options) .then (res = > {}) .catch (err = > {})

In this way, the business code can be written in the callback function of then. The core implementation code of the component is as follows:

/ / confirm.vue / /... Export default {data () {return {show: false,}}, methods: {ok () {this.show = false; this.resolve ();}, cancel () {this.show = false; this.resolve ();},}} / / index.jsimport Vue from 'vue';import options from'. / confirm.vue';const Confirm = Vue.extend (options); let confirm = undefined Const ConfirmInit = (options = {}) = > {return new Promise ((resolve, reject) = > {options.resolve = resolve; options.reject = reject; confirm = new Confirm ({el: document.createElement ('div'), data: options}) document.body.appendChild (confirm.$el); Vue.nextTick () = > {if (confirm) confirm.show = true;} return confirm;})} Vue.prototype.$confirm = ConfirmInit / / main.jsimport 'components/confirm/index.js';// global registration double confirmation pop-up confirm components 2, extract business components by module

A page can be divided into multiple areas, such as head, bottom, sidebar, merchandise list, member list, and so on. Each area can be used as a module to extract business components.

3. Extract functional components by function

After the business components are extracted by the module, the business components may still be very large, so it is necessary to further extract the functional components according to the function.

The functions are big and small, so we should pay attention to several principles in extraction:

Functions that are too simple are not extracted:

For example, a collection of functions, as long as a request for an interface to complete, such functions should not be extracted. The function of logical operation must be extracted with a certain degree of complexity.

The function should be single:

A functional component handles only one business.

For example, a file reader component, there is a requirement to open the file after the automatic collection of the file, then where to write the collection logic code?

Maybe you didn't even think about writing the favorite logic code in the method of successfully opening the listening file in the component. After a period of time, the requirement is changed to add it to the reading record and then click the favorites button. When you modify the code in the component, you find that another page also references this component, so you need to add an additional parameter in the component to distinguish between business scenarios. With the change of requirements, it leads to the superposition of business scenarios. A variety of judgment logic is added to the code of the component, which becomes long and smelly over time, which is obviously impossible.

The right thing to do is to customize an event on-fileOpen-success on the component tag and use the handleFileOpenSuccess function to listen for the event.

Execute this.$emit ('on-fileOpen-success',data) to trigger this event in the method of listening for the file to be opened successfully in the component, where data can pass out the file information and handle business interactions such as collecting or adding history records and collecting again in the handleFileOpenSuccess function. This approach makes the file reader component unique.

The functional components contain as few UI parts as possible, and the UI part is passed in by slot slots, which makes the components purer and more reusable.

For example, for the upload icon of the upload component, it is impossible to add an upload icon to it as the UI design changes. You can use the slot slot to pass in the upload icon.

/ / upload.vue / / index.vue / / upload icon 2. Use v-bind to make the properties of the component more readable

If you want to pass all the properties of an object into the component componentA as prop, you can use v-bind with no parameters. For example, for a given object params:

Params: {id: 1, name: 'vue'}

Before optimization:

After optimization:

Third, use attrs and attrs and listeners to encapsulate third-party components 1, $attrs

In encapsulating third-party components, we often encounter the problem of how to use the properties and events of third-party components through the encapsulated components.

For example, myInput, an Input input box component in an elementUi component, displays an error prompt at the bottom of the input box when the input error is entered.

The myInput component code is as follows:

{{errorTip}} export default {props: {value: {type: String, default:',}, errorTip: {type: String, default:',}}, data () {return {}}, computed: {input: {get () {return this.value} Set (val) {this.$emit ('input', val)}

This invokes the myInput component, where errorTip enters the wrong prompt for the input box.

How do you do this if you want to add a disabled attribute to the myInput component to disable the input box? Most students will do this.

{{errorTip}} export default {props: {/ /... Disabled: {type: Boolean, default: false}}, / /...}

After a period of time, you have to add other attributes of the el-input component to the myInput component, there are more than 27 el-input components in total, so how should you use prop to transmit it one by one, which is not only poor readability and tedious, you can use $attrs to put it in place in one step, let's take a look at the definition of attrs first.

Attrs: contains attribute 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 binding = "$attrs"

V {{errorTip}}

That's not enough. You have to set the inheritAttrs option to false. Why, just take a look at the definition of the inheritAttrs option.

By default, parent-scoped attribute bindings (attribute bindings) that are not considered props will be "fallback" and applied to the root element of the child component as a normal HTML attribute. When writing a component that wraps a target element or another component, this may not always behave as expected. By setting inheritAttrs to false, these default behaviors will be removed. These attribute can be made effective with $attrs, and can be explicitly bound to non-root elements through v-bind. Note: this option does not affect class and style bindings.

To put it simply, setting inheritAttrs to false,v-bind= "$attrs" does not take effect.

{{errorTip}} export default {inheritAttrs: false, props: {value: {type: String, default:',}, errorTip: {type: String, default:',}}, data () {return {}, computed: {input: {get () {return this.value} Set (val) {this.$emit ('input', val)}

In this way, you can clearly distinguish between the properties of the el-input component and the properties of the myinput component, and the readability of the props option of the component is greatly improved.

2. $listeners

So how to implement custom events on myIpput components using el-input components? maybe your first reaction is this.$emit.

{{errorTip}} export default {/ /... Methods: {blur () {this.$emit ('blur')}

El-input component has four custom events, not much, if you encounter more custom events of third-party components, how to do, add one by one, will not only add a bunch of unnecessary methods, and poor readability is easy to mix with myInput's own methods. In fact, you can use $listeners in one step. Let's take a look at the definition of $listeners.

Listeners: contains the v-on event listeners in the parent scope (without the .native modifier). It can be passed in to internal components via vMuon = "$listeners".

{{errorTip}} export default {/ /...}

In the myInput component, you can use events customized by the el-input component on the myInput component simply by adding vmuron = "$listeners" to the el-input component.

Thank you for reading this article carefully. I hope the article "sample Analysis of Vue Code Readability" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you 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: 273

*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