5.30
1.插槽slot
如果想更好的进行组件复用,那么插槽就是必不可少的,有了插槽,就可以自由定义组件内的各种标签,
在复用的时候,使用默认的公用的标签,然后通过插槽,再自定义特有的功能样式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <div class="app"> <cpn> <template v-sort:center> <span>hahaha</span> </template> </cpn>
</div> <template id="cpn"> <div> <slot name="left"></slot> <slot name="center"></slot> <slot name="right"></slot> </div> </template>
|
如上述例子中,对每个插糟进行name的绑定,然后再父组件中调用的时候,对插槽进行选择,对选中的插槽进行样式修改
注意上述例子有废弃内容,不能再标签中添加slot=""而是需要使用一个template模板中,定义v-sort
作用域插槽:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <div class="app"> <cpn> <template #center="center"> <span>{{center.user}}</span> </template> </cpn>
</div> <template id="cpn"> <div> <slot name="left"></slot> <slot name="center" :user="user"></slot> <slot name="right"></slot> </div> </template>
|
其中,v-sort可以被简写为#,通过这种方式,就可以在实例化组件中使用组件内部的各种数据。
解构方法:(当提供多个prop的时候优点就会体现出来)
1 2 3
| <current-user v-slot="{ user }"> {{ user.firstName }} </current-user>
|
也可进行重名:
1 2 3
| <current-user v-slot="{ user: person }"> {{ person.firstName }} </current-user>
|
2.依赖注入:
当你想使用其他的组件的数据和方法的时候,可以使用依赖注入
首先先使用provide指定向为其他组件提供的数据和方法
1 2 3 4 5
| provide:function(){ return{ getMap:this.getMap } }
|
然后在其他组件中,使用inject来接受这个方法或者数据
下面是官方给出的示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| Vue.component("google-map", { provide: function() { return { getMap: this.getMap }; }, data: function() { return { map: null }; }, mounted: function() { this.map = new google.maps.Map(this.$el, { center: { lat: 0, lng: 0 }, zoom: 1 }); }, methods: { getMap: function(found) { var vm = this; function checkForMap() { if (vm.map) { found(vm.map); } else { setTimeout(checkForMap, 50); } } checkForMap(); } }, template: '<div class="map"><slot></slot></div>' });
Vue.component("google-map-marker", { inject: ["getMap"], props: ["places"], created: function() { var vm = this; vm.getMap(function(map) { vm.places.forEach(function(place) { new google.maps.Marker({ position: place.position, map: map }); }); }); }, render(h) { return null; } });
|