一、模仿element-ui中this.$message()方式創(chuàng)建全局插件
vue2.x環(huán)境下:寫(xiě)好的任意組件VantAlert.vue,需要注冊(cè)全局組件:
1、首先創(chuàng)建vantAlert.js文件開(kāi)發(fā)插件:
此文件暴露出一個(gè)擁有install方法的對(duì)象,install方法的第一個(gè)參數(shù)是Vue構(gòu)造器囤采,第二個(gè)參數(shù)option是可選的對(duì)象參數(shù)。使用vue.use()可以直接調(diào)用install方法。
import VantAlert from './VantAlert.vue'
export default {
install: (Vue) => {
// 利用Vue.extend創(chuàng)建構(gòu)造器
const CommentAlert = Vue.extend(VantAlert)
// 實(shí)例化組件
const instance = new CommentAlert()
// 為vue原型添加$commentAlert方法
Vue.prototype.$commentAlert = (options = {}) => {
// 掛載組件
instance.$mount()
// 將組件元素添加到body中
document.body.appendChild(instance.$el)
// 改變實(shí)例中data的值
instance.show =true
}
}
}
2畜挥、在main.js文件中導(dǎo)出的方法放到vue的原型鏈上
// main.js中引入函數(shù)文件
import vantAlert from "./components/commentAlert/component/vantAlert";
//使用插件,Vue.use應(yīng)該在new Vue()之前調(diào)用婴谱,并且Vue.use會(huì)阻止多次注冊(cè)相同組件蟹但,即使多次調(diào)用也只會(huì)注冊(cè)一次該組件。
Vue.use(vantAlert)
3谭羔、使用
this.$vantAlert({content:‘傳遞的參數(shù)’})
4华糖、注冊(cè)的組件內(nèi)正常編寫(xiě)代碼:傳遞過(guò)來(lái)的參數(shù)data接收
export default {
name:"VantAlert",
data() {
return {
show:true,
content:'默認(rèn)的內(nèi)容', //能夠接收傳遞過(guò)來(lái)的參數(shù)
showTitle:false
}
}
}
vue3.0環(huán)境下:只是寫(xiě)法上稍微有些不同:
1、vantAlert.js文件更改如下
import {createApp } from 'vue'
import VantAlert './VantAlert.vue'
const vantAlert=function(options = {}) {
//注冊(cè)組件,并接收傳遞的參數(shù)
let messageConstructor =createApp(VantAlert, { ...options })
//將組件掛載到body下瘟裸,instance.$el是需要掛載的組件
messageConstructor.mount('body')
}
export default vantAlert
2客叉、main.js中將組件方法綁定到原型鏈上:
import {createApp } from 'vue'
import App from './App.vue'
import vantAlertfrom './components/vantAlert'
const app =createApp(App)
app.config.globalProperties.$vantAlert=vantAlert
3、使用傳參數(shù)跟vue2.x一樣
4景描、組件內(nèi)接收參數(shù)通過(guò)props接收參數(shù)
export default {
name:"index",
props: {
content: {
type:String,
default:'暫無(wú)文案'
}
}
}