In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-04-11 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/01 Report--
This article shares with you the content of a sample analysis of Mixin mixing in Vue. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
1. What is Mixin?
If we want to use a thing or tool, we must first understand what it is, so that we can prescribe the right medicine to the case.
In fact, Mixin is not exclusive to Vue, it can be said that it is an idea, it can also be said that it means mixing, in many development frameworks have implemented Mixin (mixing), we are mainly talking about Mixin in Vue here.
The old rule is to look at the official documents first.
Official explanation:
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.
Official explanations are usually obscure because they have to be professional and accurate.
We can use our own easy-to-understand words to talk about what Mixin is in Vue.
Folk explanation:
Extract the common logic or configuration of the component, and when which component needs to be used, mix the extracted part directly into the component. This reduces code redundancy and makes it easier to maintain later.
It is important to note here that logic or configuration is extracted, not HTML code and CSS code. In fact, we can also think differently, mixin is the component in the component, Vue componentization makes our code more reusable, then there is repetition between components, we use Mixin to extract again.
2. What is the difference between Mixin and Vuex?
The above point says that Mixin is a function of pulling away from the public part. In Vue, Vuex state management seems to do the same thing, pulling out the data that may be shared between components. The two look the same, but there are still slight differences. The differences are as follows:
Vuex Common State Management: if you change a piece of data in Vuex in one component, all other components that reference that data in Vuex will change as well.
The data and methods in Mixin are independent, and the components do not affect each other after use.
3. How to use it?
We understand the concept of Mixin, so how to use it? That's our point.
3.1 preparation work
Next, our mixin will be demonstrated in Vue2.x 's scaffolding project.
Initialize the simplest project with Vue-cli:
3.1 mixin definition
Defining mixin is also very simple, it is just an object, but this object can contain some common configurations in Vue components, such as data, methods, created, and so on.
Create a new mixin folder under our project src directory, and then create a new index.js file that holds our mixin code.
The code is as follows:
/ / src/mixin/index.jsexport const mixins = {data () {return {};}, computed: {}, created () {}, mounted () {}, methods: {},}
You can see that our mixin is very simple, mainly containing the common logical structure of a Vue component.
Next, let's simply write something in mixin. The code is as follows:
Export const mixins = {data () {return {msg: "I am a piggy class",};}, computed: {}, created () {console.log ("I am the created life cycle function in mixin");}, mounted () {console.log ("I am the mounted life cycle function in mixin") }, methods: {clickMe () {console.log ("I am a click event in mixin");},},}; 3.2 Local blending
Once our public mixin is defined, the most important thing is how to use it. According to different business scenarios, we can be divided into two types: local blending and global blending. As the name implies, partial blending is somewhat similar to demand loading of components, except that when code in mixin is needed, we introduce it in the component chapter. Global blending means that I can use mixin in any component of the project.
Introducing mixin into the component is also very easy, so let's modify the App.vue component a little bit.
The code is as follows:
/ / src/App.vue
Click on my import {mixins} from ". / mixin/index"; export default {name: "App", mixins: [mixins], components: {}, created () {console.log ("component calls minxi data", this.msg);}, mounted () {console.log ("I am the mounted lifecycle function of the component")}}
The effect is as follows:
The method of introducing mixin in the previous code is also very simple, directly using the mixins attribute provided to us by vue: mixins: [mixins].
From the above code and effect, we can draw the following points:
The lifecycle function in mixin is executed in conjunction with the lifecycle function of the component.
Data data in mixin can also be used in components.
Methods in mixin can be called directly within the component.
The order in which lifecycle functions are merged and executed: first in mixin, then in components.
The question is:
Here we ask a question: if one component changes the data in mixin, will another component that references mixin be affected?
The answer is no!
We can try this:
Create a new demo component under the components folder under src, as follows:
/ / data in src/components/demo.vue mixin: {{msg}} import {mixins} from ".. / mixin/index"; export default {mixins: [mixins],}
Then introduce the demo component into the App.vue component, as follows:
Click on me to change the mixin data import {mixins} from ". / mixin/index"; import demo from ". / components/demo.vue"; export default {name: "App", mixins: [mixins], components: {demo}, created () {console.log ("component calls minxi data", this.msg);}, mounted () {console.log ("I am the mounted lifecycle function of the component") }, methods: {changeMsg () {this.msg = "I am a mutated piggy class"; console.log ("changed msg:", this.msg);},},}
Code interpretation:
We introduced mixin into the demo component and used the msg data from mixin.
Mixin is also introduced in App.vue, and click event change msg is set
Click the button to change the msg to see if there are any changes in the demo component.
The effect is as follows:
You can see that after we changed the msg in the App.vue component, the demo component shows no change, so here we conclude that the mixin in different components is independent of each other!
3.3 Global blending
The last point we use mixin is to introduce it in the required components, or we can register it globally so that we can use it directly in any component.
Modify main.js. The code is as follows:
Import Vue from "vue"; import App from ". / App.vue"; import {mixins} from ". / mixin/index"; Vue.mixin (mixins); Vue.config.productionTip = false;new Vue ({render: (h) = > h (App),}). $mount ("# app")
Then comment out the code introduced into mixin in App.vue, as follows:
Click on me to change mixin data / / import {mixins} from ". / mixin/index"; import demo from ". / components/demo.vue"; export default {name: "App", / / mixins: [mixins], components: {demo}, created () {console.log ("component calls minxi data", this.msg);}, mounted () {console.log ("I am the mounted lifecycle function of a component") }, methods: {changeMsg () {this.msg = "I am a mutated piggy class"; console.log ("changed msg:", this.msg);},},}
The effect is as follows:
It can be found that there is no difference between the effect and the local blending, which is the characteristic of the global blending.
Although it is convenient to do so, we do not recommend it. Let's take a look at an official passage:
Use global blending 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 release it as a plug-in to avoid mixing with repeated applications.
3.4 option merge
If we take a closer look at the above column, we will find a problem: the name of the property or method defined in mixin does not conflict with the name defined in the component!
So we can't help thinking, what if there is a naming conflict?
We often have conflicts when we use git to merge code, don't be afraid of conflicts, let's merge. The conflicts here are mainly divided into the following situations:
(1) Life cycle function
To be exact, this is not a conflict because the names of lifecycle functions are fixed, and the default merge strategy is as follows:
The above example proves that the code in the lifecycle function of mixin is executed first, and then the code inside the component is executed.
(2) 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, to borrow an official code:
Var mixin = {data: function () {return {message: 'hello', foo:' abc'} new Vue ({mixins: [mixin], data: function () {return {message: 'goodbye', bar:' def'}}, created: function () {console.log (this.$data) / / = > {message: "goodbye", foo: "abc" Bar: "def"})
You can see that the final printed message is the value of message in the component, and other non-conflicting data are naturally merged.
(3) conflict of methods
This kind of conflict is easy to encounter, after all, everyone's naming method is very easy to be the same, here is also borrowed from the official code:
Var mixin = {methods: {foo: function () {console.log ('foo')}, conflicting: function () {console.log (' from mixin')} var vm = new Vue ({mixins: [mixin], methods: {bar: function () {console.log ('bar')} Conflicting: function () {console.log ('from self')}}) vm.foo () / / = > "foo" vm.bar () / / = > "bar" vm.conflicting () / / = > "from self"
There are conficting methods in both the mixin and the component in the previous code, but when finally called in the component, the conflicting method in the component is actually called.
Of course, it's not impossible if you want to customize the merge rules, but I don't think it's necessary, it doesn't have to be so complicated in the project.
4. Advantages and disadvantages of mixin
Judging from the above example, there are many advantages of using mixin, but there are always two sides. Here are some advantages and disadvantages for your reference:
4.1 benefits
Improve code reusability
No need to transfer statu
Easy to maintain, only need to modify one place
4.2 shortcomings
Naming conflict
If abused, it is difficult to maintain at a later stage.
It is difficult to trace the source, but it is a little troublesome to troubleshoot the problem.
You can't repeat code easily.
Thank you for reading! This is the end of the article on "sample Analysis of Mixin blending in Vue". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!
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: 203
*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.