Vue 开发全局组件

(一)导语

有时候项目中有一些组件,比如 loading、toast等等,经常用到的,可以封装好,注册成全局组件,这时候就要使用vue的指令

Vue.extend

以 toast 为例子,开发一个 toast 全局组件,只是简易版的哈,弹出来然后消失那种

(二)目录结构

toast.vue:主要是写html  以及 样式等

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

<script>
export default {
  data () {
    return {
      show: false,
      message: ''
    }
  }
}
</script>

<style scoped>
.wrapper {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  max-width: 5rem;
  line-height: 0.35rem;
  white-space: wrap;
  padding: 0.25rem;
  border-radius: 6px;
  color: #fff;
  font-size: 0.18rem;
  background: rgba(0,0,0, 0.8)
}
</style>

用到的数据要写在 data 里面,不要写在 props 里

toast.js :把封装好的toast 组件暴露出来,以及组件中的js

import Vue from 'vue'
import toast from './Toast.vue' // 引入组件
const ToastComponent = Vue.extend(toast) // 创建构造器

let timer = null
let Toast = function (message, time = 3000) {
  // 实例化子组件,然后获取到DOM结构并挂载到body上
  const toastInstence = new ToastComponent()
  // 更改组件中 data 的值
  toastInstence.show = true
  toastInstence.message = message
  // toast 挂到 body
  document.body.appendChild(toastInstence.$mount().$el) // $mount().$el
  // 关闭
  timer = setTimeout(() => {
    toastInstence.show = false
    clearInterval(timer)
  }, time)
}

export default Toast

main.js:挂载到全局

import toast from './common/toast/Toast.js'
Vue.prototype.toast = toast

使用:

this.toast(11111)

(三)Vue.extend 指令

使用基础 Vue 构造器,创建一个“子类”。参数是一个包含组件选项的对象。

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值