组件同级目录下新建func-notification.js
import Notification from './notification.vue'
export default {
extends: Notification
}
组件同级目录下新建function.js
import Vue from 'vue'
import Components from './func-notification.js'
const NotificationConstructor = Vue.extend(Components)
const notify = (options) => {
if (Vue.prototype.$isServer) return //服务端环境不使用
const instance = new NotificationConstructor({})
}
export default notify
动态添加style
notification.vue
<div class="notification" :style="style">
<span class="container">{{content}}</span>
<a class="btn" @click.stop.prevent="handleClose">{{btn}}</a>
</div>
computed: {
style () {
return {}
}
}
func-notification.js 利用extends覆盖style
computed: {
style () {
return {}
}
}
function.js:
定位位置 :根据instance的数量和位置来判断 所以要创建一个instance组和每个instance的id
const instances = []
let seed = 1
const notify = (options) => {
...
const id = `notification_${seed++}`
instance.id = id
instance.vm = instance.$mount() //返回实例自身vm
document.body.appendChild(instance.vm.$el) //如果没有提供参数,模板将被渲染为文档之外的的元素,必须使用原生 DOM API 把它插入文档中
}
计算高度:
const notify = (options) => {
...
let verticalOffset = 0
instances.forEach(item => {
verticalOffset += item.$el.offsetHeight + 16
})
verticalOffset += 16
instance.verticalOffset = verticalOffset
instances.push(instance)
return instance.vm
}
func-notification.js
新增verticalOffset属性声明和计算style
computed: {
style () {
return {
position: 'fixed',
right: '20px',
bottom: `${this.verticalOffset}px`
}
}
},
data () {
return {
verticalOffset: 0
}
}
使用api形式调用
组件同级目录下 index.js
import Notification from './notification.vue'
import notify from './function.js'
export default (Vue) => {
Vue.component(Notification.name, Notification)
Vue.prototype.$notify = notify
}
在vue文件夹下的vue文件中
methods: {
notify () {
this.$notify({
content: 'this is $notify',
btn: 'close'
})
}
}
function.js: 接受参数
const notify = (options) => {
...
const instance = new NotificationConstructor({
propsData: options
})
}
在vue文件夹下的vue文件中 为了演示多个 通过方法生成
<button @click="notify">click</button>
methods: {
notify () {
this.$notify({
content: 'this is $notify',
btn: 'close'
})
}
}
至此 通过vue对象上调用api生成组件已经完成,之后是完善功能。