组成 Vue.js 组件

Vue.js的一个常被忽视的功能是组件组成,它允许您以最小的努力扩展和继承一个或多个组件,以便在您的应用中提供可重复使用的功能。

扩展通过将其他组件的选项与您的组件合并而起作用. 重复属性将被您的组件重写,重复方法将被一个接一个命名。

扩展

扩展允许您扩展一个单一的其他组件,您的组件的选项优先于母组件,这意味着,例如,如果母组件和您的组件都包含创建()粘合物,您的组件的创建()粘合物将首先被调用,然后是母组件。

1[label ParentComponent.vue]
2<script>
3export default {
4  created() {
5    console.log('Created from the parent!');
6  }
7}
8</script>
 1[label ChildComponent.vue]
 2<script>
 3import ParentComponent from './ParentComponent.vue';
 4
 5export default {
 6  extends: ParentComponent,
 7
 8  created() {
 9    console.log('Created from the child!');
10  }
11}
12</script>

出发点:**

1Created from the child!
2Created from the parent!

混合物

混合物更酷,它们允许您扩展 多种组件定义。使用混合物,您可以简单地在任何组件中提供可重复使用的方法和数据。

唯一的主要区别是,混合链接被称为顺序,而不是您的组件的自身链接。

 1[label my-mixins.js]
 2export const mixin1 = {
 3  created() {
 4    console.log('Created Mixin 1');
 5  }
 6}
 7
 8export const mixin2 = {
 9  created() {
10    console.log('Created Mixin 2');
11  }
12}
13
14export const mixin3 = {
15  mounted() {
16    console.log('Mounted Mixin 3');
17  }
18}
19
20export const mixin4 = {
21  mounted() {
22    console.log('Mounted Mixin 4');
23  }
24}
 1[label ChildComponent.vue]
 2<script>
 3import {mixin1, mixin2, mixin3, mixin4} from './my-mixins.js';
 4
 5export default {
 6  mixins: [mixin1, mixin2, mixin3, mixin4],
 7
 8  created() {
 9    console.log('Created from the child!');
10  },
11
12  mounted() {
13    console.log('Mounted from the child!');
14  }
15}
16</script>

出发点:**

1Created Mixin 1
2Created Mixin 2
3Created from the child!
4
5Mounted Mixin 3
6Mounted Mixin 4
7Mounted from the child!

全球混合物

Mixins 也可以在全球范围内注册,将其功能注入到每个 Vue 组件中,这可能有助于日志或调试,但通常不会在插件之外使用。

要创建一个全球混合,请使用 Vue.mixin 注册它。

1import Vue from 'vue';
2
3Vue.mixin({
4  created() {
5    // Will be called every time a component is created.
6    console.log('Mixin created!');
7  }
8})
Published At
Categories with 技术
Tagged with
comments powered by Disqus