弹窗组件
这个vue2和vue3是一样的
<template>
<div v-if="active" class="alert">
<div class="alert-box">
{{ text }}
</div>
</div>
</template>
<script>
export default {
data() {
return {
active: false,
text: '',
timer: null
}
},
methods: {
info(text) {
console.log(this);
this.text = text;
this.active = true;
if (this.timer) {
clearTimeout(this.timer);
this.timer = null;
}
this.timer = setTimeout(() => {
this.active = false;
}, 2000);
}
}
}
</script>
<style lang="less">
.alert {
position: fixed;
z-index: 9;
top: 20px;
left: 0;
right: 0;
margin: auto;
180px;
padding: 10px 16px;
border-radius: 2px;
margin: auto;
box-shadow: 0 3px 6px -4px #0000001f, 0 6px 16px #00000014,
0 9px 28px 8px #0000000d;
background-color: white;
color: black;
.icons {
position: relative;
top: 2px;
margin-right: 6px;
}
}
</style>
将组件注册为全局插件--vue2
import Alert from "./alert.vue";
export default {
install(Vue) {
// 通过Vue.extend创建子类(注意是个构造类)
const AlertCmp = Vue.extend(Alert);
// 初始化这个子类
const alertCmp = new AlertCmp();
// 将其挂载到指定dom上,也可以不写默认挂载到body上
const div = document.createElement("div");
document.body.append(div);
alertCmp.$mount(div);
// 注册全局方法,方便使用
Vue.prototype.$alert = {
info: alertCmp.info
};
},
};
使用这个插件--vue2
import Vue from 'vue'
import App from './App.vue'
import Alert from '../packages'
Vue.config.productionTip = false;
Vue.use(Alert);
const app = new Vue({
render: h => h(App)
}).$mount('#app')
以下是vue3版本的操作,
我们来对比下
将组件注册为全局插件--vue3
import { createApp } from 'vue'
import Alert from "./alert.vue";
export default {
install(app) {
// 通过createApp创建子类实例 并挂载
const div = document.createElement("div");
document.body.append(div);
const alertApp = createApp(Alert).mount(div)
// 注册全局方法,方便使用
app.config.globalProperties.$alert = {
info: alertApp.info
};
}
};
使用这个插件--vue3
import { createApp } from 'vue'
import App from './App.vue'
import alertGoodVue3 from '../packages'
const app = createApp(App).use(alertGoodVue3).mount('#app')