Vue.extend详解,自定义toast弹窗

Vue.extend详解,自定义toast弹窗Vue.extend方法,返回的是一个扩展实例构造器可以理解为组件类的一个构造函数,其属性都为组件内的对应的属性//定义一个组件的构造函数constdivComponent=Vue.extend({ template:`<divv-on:click=”click”>{{text}}</div>`, data(){ return{ text:’helloword’ } }, methods:{ click(){ consol

大家好,又见面了,我是你们的朋友全栈君。如果您正在找激活码,请点击查看最新教程,关注关注公众号 “全栈程序员社区” 获取激活教程,可能之前旧版本教程已经失效.最新Idea2022.1教程亲测有效,一键激活。

Jetbrains全系列IDE稳定放心使用

Vue.extend方法,返回的是一个扩展实例构造器

可以理解为组件类的一个构造函数,其属性都为组件内的对应的属性

//定义一个组件的构造函数
const divComponent = Vue.extend({ 
   
	template:`<div v-on:click="click">{ { text } }</div>`,
	data() { 
   
		return { 
   
			text: 'hello word'
		}
	},
	methods:{ 
   
		click(){ 
   
			console.log("click")
		}
	}
})
//调用new方法 实例化组件并挂载dom上
new divComponent().$mount('#app');
//或者直接传入一个el参数来挂载
new divComponent({ 
   el:"#app"})
好比当我想自定义一个toast弹窗,即可使用Vue.extend实现
//先定义好toast.vue组件模板 如下
<template>
	<div class="container">
		<div> { 
    text } </div>
	</div>
</template>
//新建toast.js 
import Vue from 'vue';
import toast from './toast.vue'
//创建构造器 将组件放进去
const ToastConstructor =  Vue.extend(toast);
//定一个触发toast显示的方法 并且写好显示的规则、参数等
function showToast(text,duration=2200){ 
   
	const toastDOM = new ToastConstructor({ 
   
		el:document.createElement("div"),
		data(){ 
   
			return{ 
   
				text:text
			}
		}
	})
	//添加到body中
	document.body.appendChild(toastDOM.$el)
	//自动消失
	setTimeout(()=>{ 
   
		let dom = toastDOM.$el
		dom.parentNode.removeChild(dom)
	},duration)
}
//按照vue规则,定义全局方法需要暴露一个 install 方法,如default导出为方法则可当做install使用 因此这样写
function toastRegistry(){ 
   
	Vue.prototype.$toast = showToast
}
export default toastRegistry
//最后在main.js中使用Vue.use(toastRegistry)引用即可
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/189942.html原文链接:https://javaforall.net

赞 (0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号