In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)05/31 Report--
This article mainly introduces "how to use mixin local blending and global blending in vuejs". In daily operation, I believe that many people have doubts about how to use mixin local blending and global blending in vuejs. Xiaobian 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 mixin in vuejs. Next, please follow the editor to study!
Demand
Suppose: now that there are two different button components, ButtonA,ButtonB, click it to pop up the different properties of the component itself.
Create a project with Vue-cli scaffolding and create two ButtonA.vue,ButtonB.vue components under the components folder
The following is the content of the ButtonA component, with the handleButton method bound to the button and defined in the methods option configuration
Button components An export default {name: "ButtonA", data () {return {name: "itclan.cn"}}, methods: {handleButton () {alert (this.name);}}. Wrap {margin-right: 20px;}
The following is the content of the ButtonB component, with the handleButton method bound to the button and defined in the methods option configuration
Button components B export default {name: "ButtonB", data () {return {name: "video.itclan.cn"}}, methods: {handleButton () {alert (this.name);}
Then introduce two ButtonA,ButtonB components into App.vue
Import ButtonA from ". / components/ButtonA" import ButtonB from ". / components/ButtonB" export default {name: 'App', components: {ButtonA, ButtonB}} # app {font-family: Avenir, Helvetica, Arial, sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale; text-align: # 2c3e50; margin-top: 60px; display: flex; justify-content: center;}
After a few lines of code above, we can achieve what we want, but you will find that their functional logic is the same, and the method names defined are all the same.
If there are many such components in a project, as long as you want to change, then all the single-file components have to be modified manually, there is no doubt that there is more repetitive code and more scattered.
For the same configuration between different components, can it be extracted and shared? in Vue, mixin is provided.
What is mixin?
The common configuration of multiple components is extracted into a blending object, and then through local blending or global blending, in order to achieve the purpose of sharing the configuration, this is mixin
Official documentation: mixin provides a very flexible way to distribute reusable functionality in Vue components. A blended object can contain any component option. When a component uses a blending object, all options that blend into the object are "blended" into the component's own options.
Extract the common logic or configuration of the component (including data, method, life cycle, even props, etc.), and when which component needs to be used, mix the extracted part directly into the component. This can not only reduce code redundancy, but also make it easier to maintain later, you can change it in one place, and you don't have to go everywhere to modify the configuration in each component.
Note: logic or configuration is extracted, not HTML code and CSS code. In other words, mixin is the component of the component, and Vue componentization makes our code more reusable.
Then there are repetitive parts between components, such as the reuse of logical business, and we can also use Mixin to extract it again.
The following has been rewritten by mixin
Create a mixin folder under the src folder (all mixed in), create a popButton.js file, create an object, and then expose it, as shown below
Export const popButton = {/ / methods: {handleButton () {alert (this.name);}, the configuration of component options, life cycle, data properties, calculation properties, listening properties, etc.
Then introduce it where the component is used, such as the ButtonA component, introduced through import, and mixins: [introduced mixed name] in the component configuration options, if multiple, separated by a comma
Button component An import {popButton} from ".. / mixin/popButton.js" export default {name: "ButtonA", mixins: [popButton], data () {return {name: "itclan.cn"}},} .wrap {margin-right: 20px;}
This is also regarded as local blending within the component through minxins: [mixing name].
Local blending only works within the current component, which is similar to demand loading, that is, when we need to use code in mixin, we introduce it into the component.
And global blending means that I can use mixin in any component of the project, from the root component to any component of it.
Global blending
Local blending is the introduction of blending in the required components, blending through import import, and through minxins: [mixing name] in the configuration options of the component
On the other hand, the global blending is introduced into the main.js in the project code and registered with Vue.mixin (mixed name).
Any of these components can be used with the mixed, as shown in the following code
Import Vue from 'vue'import App from'. / App.vue'import {popButton} from ". / mixin/popButton.js" Vue.mixin (popButton); Vue.config.productionTip = falsenew Vue ({render: h = > h (App),}). $mount ('# app')
: tip considerations should be extra careful when using global blending. Once global blending is used, it will affect every vue instance created later, that is, all vm,vc will be mixed
It is no different from local mixing. Although one-time injection mixing is very convenient, it also brings some problems. All component instances and Vue instances will be mixed.
In the official special tip, it is mentioned that global blending is used with caution, as it affects each separately created vue instance (including third-party components)
In most cases, it should only be applied to custom options, as in the example above, it is recommended to publish it as a plug-in to avoid repeated application mixing:
Several important questions
The lifecycle function in mixin is merged with the lifecycle of the component.
Data data in mixin can be used in components
Methods in mixin can be called directly within the component
The order in which lifecycle functions are merged is executed first in mixin, and then in the component
Mounted will not be merged, it will be loaded again.
The mixin in different components is independent of each other. If you change the data in mixin in one component, the other component that references mixin will not be affected.
The code is as follows
Export const popButton = {data () {return {name: "Chuanchuan", age: 18}}, created () {console.log ("mixing lifecycle starts to execute"), mounted () {console.log ("I am mixing") }, methods: {handleButton () {alert (this.name);}, handleMounted () {console.log ("loading method");}} option merge
When components and blended objects have options of the same name, these options will be merged in an appropriate manner
That is, what happens when the data defined in mixin, the method name and the property name and method name in the component have the same name?
Will there be a problem of overwriting data and method names? Who covers who? What is the order of execution?
Life cycle function
Mixin can have its own lifecycle functions. Like components, lifecycle functions are self-executing functions that are automatically executed at a certain stage.
It is fixed, and the default merge strategy is as follows
First execute the code in the lifecycle function in mixin, and then execute the code within the component
Export const popButton = {data () {return {name: "Chuanchuan", age: 18}}, beforeCreate () {console.log (before creation);}, created () {console.log ("mixing lifecycle starts execution") }, mounted () {console.log ("I am mixed in");}, beforeUpdate () {console.log (before update);}, updated () {console.log (when updated);}, beforeDestroy () {console.log (before destruction) }, destroyed () {console.log (when destroyed);}, methods: {handleButton () {alert (this.name);}, handleMounted () {console.log ("load method");}
If the method has the same name, the method in the latter component overrides the method in mixin
Data data conflict
When the data data in mixin conflicts with the data data in the component, the data data in the component will overwrite the data in mixin
If there is no same, the data will be merged.
Export const popButton = {data () {return {name: "Chuanchuan", age: 18}},} method name conflict
It is easy to encounter the same name in the same project. If the method name in mixin is the same as the method name introduced into mixin, then the current component shall prevail.
Advantages and disadvantages of mixin
Since mixin is so easy to use, why not recommend it in large numbers directly? mixin can reuse the logic of components, which can save a lot of code, but it also brings some problems.
1. The source of the variable name is not clear
In some single-file components, mixin is introduced, because the method of mixin can be called in the component and the data defined in mixin can be used to find the context. It is not so intuitive to find the context, either by reading the code to find it step by step, or globally.
When using mixin, it is not easy to read, and the code becomes difficult to maintain
Because multiple mixin can be introduced into the component, and the variables and methods in the mixin can be called directly and implicitly, it will make the code writer look a little confused and can't tell which mixin these variables and methods belong to.
So the suggestion here is: all the methods of mixin are put under the mixin folder for management.
two。 The lifecycles of multiple mixins will merge and run together, but the attributes and methods of the same name cannot be merged, which will lead to conflicts or overrides.
When a property defined in a component is encountered and the method is the same as that in minxin, the properties of the latter component will override the properties in mixin
3. There may be a many-to-many relationship between mixins and components, and the complexity will become higher.
A component can reference multiple mixins and a mixins can also be referenced by multiple components. Because it is shared logic, it is not very clear in terms of relationship.
Difficult to trace the code, troubleshooting, you can use the tool vscode global search, if it is a lot of places to use the mixin, then you have to check one by one
If mixin is misused, it will make the code difficult to maintain
If global blending is used, some properties and methods will be inexplicably added in any component when reviewing the code, which will confuse the new students. If they are familiar with mixin, it is nothing, if not familiar with it.
So it's very distressing, this variable name and method, I obviously don't have a definition in the component, but why can I use it, bring some confusion?
Be careful
If a function, logic, is certain from the beginning that it will not move in the future, then mixin can be used.
Advantages of mixin
Improve the reuse of component code
No need to transfer statu
Easy to maintain, only need to modify one place, global blending, should be used with caution
At this point, the study on "how to use mixin local blending and global blending in vuejs" 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.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.