(一)导语
有时候项目中有一些组件,比如 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 构造器,创建一个“子类”。参数是一个包含组件选项的对象。