From dfbcbc6fe3d5f654e092095475f753fa4c3626ca Mon Sep 17 00:00:00 2001 From: J4unty Date: Wed, 20 Mar 2019 15:25:19 +0100 Subject: [PATCH] Added a mixxin guide for vue (#32948) * Added a mixxin guide for vue * renamed folder to lower case * fix: corrected typo and grammar --- guide/english/vue/mixins/index.md | 101 ++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 guide/english/vue/mixins/index.md diff --git a/guide/english/vue/mixins/index.md b/guide/english/vue/mixins/index.md new file mode 100644 index 0000000000..20af411c36 --- /dev/null +++ b/guide/english/vue/mixins/index.md @@ -0,0 +1,101 @@ +--- +title: Mixins +--- + +## Mixins + +A constant problem is that we use some small functions in a lot of Vue components. Instead of copying them into each of them, we can create mixins. Those can be included and will then be merged into the current component. + +### Examples + +Let's look at the following example: + +We see here that the mixin is merged into the context of the Vue Component, data of the mixin will be merged as well. +```javascript +var myMixin = { + methods: { + hello: function(name) { + return "Hello " + name; + } + } +}; + +new Vue({ + mixins: [myMixin], + created: function() { + console.log(this.hello("John")); + } +}); + +// this will return print: Hello John +``` + +```javascript +var myMixin = { + created: function() { + console.log("running mixin constructor"); + } +}; + +Here we see that the constructor of the mixin is always executed before that of the component. +new Vue({ + mixins: [myMixin], + created: function() { + console.log("running component constructor"); + } +}) +// this will print: +// running mixin constructor +// running component constructor +``` + +Here we see that the Component will override the definitions in the mixin if there is a conflict. +```javascript +var myMixin = { + methods: { + foo: { + console.log('mixin foo'); + }, + bar: { + console.log('mixin bar'); + } + } +}; + +var comp = new Vue({ + mixins: [myMixin], + methods: { + bar: function() { + console.log('component bar'); + } + } +}); + +comp.foo(); // prints "mixin foo" +comp.bar(); // prints "component bar" +``` + +In this case we can use it to make a global readOnly Variable +```javascript +// use global mixins carefully +Vue.mixin({ + data: function() { + return { + get greeting() { + return "World"; + } + } + } +}); + +Vue.component('page-greeting', { + props: , + template: ` +
+

+ Hello {{ greeting }} +

+
+ ` +}); +```