VUE 如何将一个组件封装成一个插件

vue中的组件可以以普通的方式封装,也可以以插件的方式封装:

vue中插件的封装

举例封装一个toast插件:

1.创建toast组件

创建一个toast文件夹./toast,里面建index.js

import Toast from './toast'
const obj = {}
obj.install=function (Vue) {
  //1.创建组件构造器
  const toastConstrstor = Vue.extend(Toast)
  //2.new的方式,根据组件构造器,可以创建出来一个组件对象
  const toast = new toastContrustor()
  //3.将组件对象手动挂载到div上
  toast.$mount(document.createElement('div'))
  //4.toast.$el对应的就是上面的div
  document.body.appendChild(toast.$el)
  Vue.prototype.$toast=Toast
}
export default obj

将toast对象保存到Vue的原型中,那么vue实例就都可以通过$toast访问到,在组件中,通过this.$toast访问 

toast/toast.vue

<template>
<div v-if="show">{{message}}</div>
</template>

<script>
  export default {
    name: "toast",
    data(){
      return {
        message:'',
        show: false
      }
    },
    methods:{
      show(message,duration ){
          this.show=true
          this.message=message
        setTimeout(()=>{
          this.show=false
          this.message=''
        },duration)
      }
    }
  }
</script>

2.在main.js中导入,安装

import toast from './toast'
Vue.use(toast)

当Vue.use(toast) 时,会调用toast对象内的install()函数,并将vue对象传递过去

3.使用

this.$toast.show('你好',true)

通过ths.$toast访问toast组件中的show方法,就可改变isShow的属性,展示toast组件

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值