使用Api的形式封装Vue组件(二)

组件同级目录下新建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生成组件已经完成,之后是完善功能。



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值