Recently, when I was working on a project, I studied mixins, and this function is wonderful. When using it, there is a scenario where the page style is different, but the execution method is very similar to the required data. Do we want to write two components? Or should one be kept and then the other one is compatible with the other?
No matter the above method, it is not very reasonable, because writing the component into two is not only troublesome but also troublesome to maintain; although the second type is compatible, the page logic causes confusion and will inevitably be unclear; Is there a good way? There is a mixin of vue that is mixed plug-in mixins. Mixed in Vue is to propose similar data and functions, making the code easy to understand, simple and clear.
1. Scene
Suppose we have several different components whose job is to switch state booleans, modals, and tooltips. These hints and modal verbs don't have much in common, except for the function: they look different, they are not used to the same, but the logic is the same.
//Popular boxconst Modal = { template: '#modal', data() { return { isShowing: false } }, methods: { toggleShow() { = !; } }, components: { appChild: Child } } // Prompt boxconst Tooltip = { template: '#tooltip', data() { return { isShowing: false } }, methods: { toggleShow() { = !; } }, components: { appChild: Child } }
The above is a pop-up box and a prompt box. If you consider making 2 components, or one is compatible with the other, it is not a reasonable way. Please look at the code
const toggle = { data() { return { isShowing: false } }, methods: { toggleShow() { = !; } } } const Modal = { template: '#modal', mixins: [toggle], components: { appChild: Child } }; const Tooltip = { template: '#tooltip', mixins: [toggle], components: { appChild: Child } };
Use mixins to introduce js files with similar to toggle functions for mixing
2. Life cycles can be merged
//mixin const hi = { mounted() { ('this mixin!') } } //vue componentnew Vue({ el: '#app', mixins: [hi], mounted() { ('this Vue instance!') } }); //Output in console > this mixin! > this Vue instance!
The data output from mixins is first
3. Can be mixed globally (similar to filter)
({ mounted() { ('hello from mixin!') }, method:{ test:function(){ } } }) new Vue({ el: '#app', mounted() { ('this Vue instance!') } })
The log in the cycle will be agreed in each component, and the methods inside are similar to the method of adding instances in vue's prototype.
var install = function (Vue, options) { // 1. Add global methods or properties = function () { // Logic... } // 2. Add global resources ('my-directive', { bind (el, binding, vnode, oldVnode) { // Logic... } ... }) // 3. Inject components ({ created: function () { // Logic... } ... }) // 4. Add an instance method .$myMethod = function (options) { // Logic... } }
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.