快速原型开发
免于vue文件的繁杂配置,或者脚手架下载依赖的时间,这次让我们轻装上阵来实现一个notification弹框。1
2
3
npm install -g @vue/cli @vue/cli-service-global
npm i less less-loader -D
vue serve
就可以启动了。
用的vue方法api
Vue.extend
这是一个基础Vue构造器,创建一个“子类”。参数是一个包含组件选项的对象(同单文件.vue的参数,或者.vue文件导出的对象)。1
2
3
4
5
6
7
8
9
10
11
12
13// 创建构造器
var Profile = Vue.extend({
template: '<p>{{firstName}} {{lastName}} aka {{alias}}</p>',
data: function () {
return {
firstName: 'Walter',
lastName: 'White',
alias: 'Heisenberg'
}
}
})
// 创建 Profile 实例,并挂载到一个元素上。
new Profile().$mount('#mount-point')
extends:允许声明扩展另一个组件(可以是一个简单的选项对象或构造函数),而无需使用 Vue.extend。这主要是为了便于扩展单文件组件。使用他的原因是因为,可以在基础的notifation组件基础扩展一个新的组件来实现api式调用,而不会影响原来组件的正常使用
。1
2
3
4
5
6
7var CompA = { ... }
// 在没有调用 `Vue.extend` 时候继承 CompA
var CompB = {
extends: CompA,
...
}
项目介绍
项目基本目录,App.vue是跟组件,components 文件夹是notifation的实现逻辑
基础组件(notification.vue)
- 组件接受
content
来展示自定义内容。 - @after-leave 动画结束钩子
- 鼠标事件 主要是为了 后面的独立组件(function_notify)扩展,为了实现 鼠标停留在notifation组件展示,鼠标离开后,组件默认3秒自动消失
1 | <template> |
独立扩展组件(function_notify.js)
- screenBottom 记录组件离屏幕底部的距离;timeClock,组件自动消失的时间间隔
- style覆盖基础组件的样式
1 | import Notification from './notification.vue'; |
notify方法的实现(notification.js)
- 通过Vue.extend得到了一个构造方法
- instanceArr 收集所有的实例;gap 组件之间的间隔
- 监听‘close’和‘leaved’事件,销毁实例
- 函数detoryIntance,销毁实例方法。
- 要在dom渲染后再获取元素的 offsetHeight
1 | import Vue from 'vue'; |
效果预览
最后我们点击页面按钮,组件就会屏幕右下方展示了。
App.vue
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<template>
<div>
<button @click="showNotify">notify</button>
<!-- 测试组件样式 -->
<!-- <Notification></Notification> -->
</div>
</template>
<script>
// import Notification from "./components/notification.vue";
import { notify } from "./components/notification.js";
export default {
name: "app",
// components: {
// Notification
// },
methods: {
showNotify() {
notify({
content: "hello world!"
});
}
}
};
</script>