javaScript Vue2的高级用法
一.mixin的复用
混入 (mixin) 提供了一种非常灵活的方式,来分发 Vue 组件中的可复用功能。一个混入对象可以包含任意组件选项。当组件使用混入对象时,所有混入对象的选项将被“混合”进入该组件本身的选项。
var mixin = {
data: function () {
return {
message: 'hello',
foo: 'abc'
}
}
}
new Vue({
mixins: [mixin],
data: function () {
return {
message: 'goodbye',
bar: 'def'
}
},
created: function () {
console.log(this.$data)
// => { message: "goodbye", foo: "abc", bar: "def" }
}
})
注意:同名钩子函数将合并为一个数组,因此都将被调用。另外,混入对象的钩子将在组件自身钩子之前调用。
值为对象的选项,例如 methods
、components
和 directives
,将被合并为同一个对象。两个对象键名冲突时,取组件对象的键值对。
1.1 全局混入
混入也可以进行全局注册。使用时格外小心!一旦使用全局混入,它将影响每一个之后创建的 Vue 实例。使用恰当时,这可以用来为自定义选项注入处理逻辑。
// 为自定义的选项 'myOption' 注入一个处理器。
Vue.mixin({
created: function () {
var myOption = this.$options.myOption
if (myOption) {
console.log(myOption)
}
}
})
new Vue({
myOption: 'hello!'
})
// => "hello!"
二.插槽
2.1默认插槽
我们在编写代码时,组件内部并不清楚这块内容的具体实现,我就需要将这个坑位留出,需要开发者传进来。
<div class="container">
<main>
<slot></slot>
</main>
</div>
2.2具名插槽
带有名称的插槽,用于接收父组件中明确指定插槽名称的内容。
<div class="container">
<header>
<slot name="header"></slot>
</header>
</div>
2.3作用域插槽
一种特殊的插槽,允许子组件将数据暴露给父组件的插槽内容。
子组件:
<template>
<ul>
<li v-for="item in items" :key="item.id">
<slot name="item" :item="item">
<!-- 后备内容 -->
{{ item.text }}
</slot>
</li>
</ul>
</template>
<script>
export default {
data() {
return {
items: [
{ id: 1, text: '苹果' },
{ id: 2, text: '香蕉' },
{ id: 3, text: '橙子' }
]
}
}
}
</script>
父组件:
<template>
<ScopedSlotChild>
<template v-slot:item="slotProps">
<!-- 使用slotProps访问子组件传递的数据 -->
<strong>{{ slotProps.item.text }}</strong>
</template>
</ScopedSlotChild>
</template>
<script>
import ScopedSlotChild from './ScopedSlotChild.vue';
export default {
components: {
ScopedSlotChild
}
}
</script>
三.插件
插件可以是对象,或者是一个函数。如果是对象,那么对象中需要提供 install 函数,如果是函数,形态需要跟前面提到的 install 函数保持一致。
install 是组件安装的一个方法,跟 npm install 完全不一样,npm install 是一个命令
const MyPlugin = {
install(Vue, options) {
// 1. 添加全局方法或 property
Vue.myGlobalMethod = function () {
// 逻辑...
}
// 2. 添加全局资源
Vue.directive('my-directive', {
bind (el, binding, vnode, oldVnode) {
// 逻辑...
}
...
})
// 3. 注入组件选项
Vue.mixin({
created: function () {
// 逻辑...
}
...
})
// 4. 添加实例方法
Vue.prototype.$myMethod = function (methodOptions) {
// 逻辑...
}
}
};
使用插件:
Vue.use(MyPlugin);
{{ $myMethod }}