- Vue.extend 和 Vue.component 的区别
component
是需要先注册,然后再template
中使用,在开发过程中会遇到需要在js里面来操作组件的情况。于是就有了Vue.extend
,extend
是编程式的写法,通过手动操作组件的挂载和销毁。
- 首先先创建一个
toast
弹窗的vue
组件,这里没什么好说的,vue
的基本语法
Toast.vue
<template>
<div v-if="showToast">
<div class="toastTip">
<p class="title"> {{ tipTitle }} </p>
<p class="context"> {{toastTxt }} </p>
<div class="add-button">
<Button v-if="showCancel" class="btn-cen" @click="cancel">取 消</Button>
<Button class="btn-confirm" style="margin-left: 10px;" type="primary" @click="ok">确 定</Button>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'toastTip',
methods: {
ok() {
this.onOk();
this.showToast = false;
},
cancel() {
this.onCancel();
this.showToast = false;
}
},
props: {
toastTxt: {
type: String,
default: ""
},
showToast: {
type: Boolean,
default: true
},
showCancel: {
type: Boolean,
default: true
},
tipTitle: {
type: String,
default: '操作确认'
},
onOk: Function,
onCancel: Function
}
}
</script>
<style lang="less">
.tip-box {
display: flex;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
background-color: rgba(43, 60, 77, 0.9);
z-index: 999;
}
.toastTip {
background: #fff;
border-radius: 5px;
width: 400px;
min-height: 200px;
text-align: center;
position: fixed;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
z-index: 500;
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 10px;
.title {
font-size: 25px;
font-weight: 800;
}
.context{
font-size: 16px;
flex-grow: 1;
text-align: left;
text-indent: 2em;
padding: 10px;
}
.add-button {
display: flex;
justify-content: flex-end;
padding: 0 10px 10px 0;
.btn-cen {
height : 36px;
background : #d3dbdf;
color : #fff;
border : none;
border-radius: 0;
padding: 0 20px;
cursor: pointer;
&:hover {
border : none;
background: #d3dbdf;
}
}
.btn-confirm {
height : 36px;
background : rgb(23, 164, 161);
color : #fff;
text-align : center;
border : none;
border-radius: 0;
padding: 0 20px;
cursor: pointer;
&:hover {
border : none;
background: rgb(23, 164, 161);
}
}
}
}
</style>
- 其次创建完组件以后,将通过
extend
创建一个vue
子类。下面定义一个toastMsg
函数对象,并实例化(参数为vue
组件选项)。
Toast.js
import Vue from 'vue'
import toastMsg from './toast.vue'
// 创建子类
const tipBox = Vue.extend(toastMsg);
toastMsg= function (data) {
//实例化,在这里vue源码中是将propsData遍历赋值给props,所以在toast.vue中需要用props接收
let instance = new tipBox({
propsData: data
});
// 生成$el未挂载
instance.$mount();
// 增加class
instance.$el.className = 'tip-box';
//插入body中
document.body.appendChild(instance.$el);
}
export default toastMsg.install
- 在
main.js
中引入,添加到vue
原型中,然后调用~
main.js
import toastMsg from './extend/toast/Toast'
Vue.prototype.$toastMsg = toastMsg;
Vue.prototype.$toastMsg({
tipTitle: '提示内容',
toastTxt: "马老板,汉族,1971年10月29日生于广东省东方县八所港(今属海南省东方市),广东省汕头市潮南区人 [1-2] 。1993年获深圳大学理学学士学位。腾讯公司主要创办人之一。现任腾讯公司董事会主席兼首席执行官;全国青联副主席;全国人大代表。 [3] 1984年随父母从海南迁至深圳,1993年毕业于深圳大学计算机系。同年进入深圳润迅通讯发展有限公司开始寻呼系统的研究开发工作。1995年创建惠多网深圳站,名为ponysoft。",
onOk: () => {
//回调函数
console.log(123);
},
onCancel: () => {
console.log(456);
}
});
- 实现效果