2.1 mixins
- 混入mixins是分发Vue组件中可复用的功能 非常灵活的方式。
- 混入的对象可以包含任意组件选项。
- 当组件使用混入对象,所有混入的选项都将合并到组件本身里去。
const mymixin = {
methods: {
hello(){}
}
}
//全局混入
Vue.mixin(mymixin) //注意是单个对象
//局部混入
Const Comp = {
mixins = [mymixin] // 注意用的是组数
}
复制代码
2.2 插槽主要用于Vue组件中的内容分发,也可以用于组件的扩展
2.2.1匿名插槽
子组件Child
<div>
<slot>这是子组件</slot>
</div>
复制代码
父组件Parent
<div>
<Child>这是在父组件定义的内容</Child>
</div>
复制代码
2.2.2具名插槽
通过具体的名称,可以精确分发到不同的位置。
子组件slot="xxxx"
,父组件 slot name="xxxx"
// 子组件
<template>
<section>
<slot name="article-title">这里放标题</slot>
<slot>这里放作者</slot>
<slot name="article-content">这里放文章内容</slot>
</section>
</template>
// 父组件
<template>
<section>
<slot-child>
<h1 slot="article-title">标题111</h1>
<p slot="article-content">内容222</p>
</slot-child>
</section>
</template>
复制代码
2.2.3作用域插槽
在父组件要使用子组件的内容渲染,可以使用
//子组件 ,在子组件提前注入数据 :xxx="内容"
<slot :nickName="'Tusi'"></slot>
//父组件 , 父组件可以通过 scope.xxx获取
<template>
<section>
<slot-child>
<template slot-scope="scope">
<div>{
{scope.nickName}}</div>
</template>
</slot-child>
</section>
</template>
复制代码
http://www.bilibili.com/medialist/detail/ml1406500246
http://www.bilibili.com/medialist/detail/ml1406245446
http://www.bilibili.com/medialist/detail/ml1405997146
http://www.bilibili.com/medialist/detail/ml1405899546
http://www.bilibili.com/medialist/detail/ml1405897646
http://www.thinksaas.cn/user/space/50002/
2.3 extends
不太常用
- 作为数组项设置 extends,仅作用与当前组件
- 只能扩展单个对象,不过可以通过多继承实现。。
- 如果混入发生冲突,优先级以原对象为主。
const myextends = {
methods: {
hello() {}
}
}
const Comp = {
extends: myextends
}
复制代码
2.4 vue3 compostion API
- 可以解决混入后,数据和方法不能明确判断来源,与当前组件内变量命名产生冲突。
- 利用独立出来的响应式模块,可以很方便的便携独立的逻辑并且提供高响应式数据。最后通过setup选项中有机组合使用。
// 复用逻辑1
function useXXX() {}
// 复用逻辑2
function useYYY() {}
// 逻辑组合
const Comp = {
setup() {
const {xx} = useXXX()
const {yy} = useYYY()
return {xx,yy}
}
}