組件在vue開發中是必不可少的,若是一個組件在多個頁面中都須要使用,那麼每次都要引入,註冊,使用,仍是有點繁瑣的。因此對那些要頻繁使用的咱們要實現一次引入,全局使用。vue
本文就帶你瞭解自定義一個全局複用的組件(Toast),在main.js中引用組件,之後只要在須要的頁面上寫一句js代碼便可實現效果。git
先看看效果github
監聽點擊事件。api
methods: {
click() {
this.$toast.show("home你好啊") //實現toast彈窗
}
}
複製代碼
咱們看看頁面的結構bash
當咱們點擊按鈕執行語句this.$toast.show("home你好啊")
, 就會動態去除
display:none;
默認信息也會改成咱們調用show函數時傳遞的
參數。
咱們要用到toast組件的時候,直接經過this.$toast調用show()方法,第一個參數是要顯示的信息,第二參數是toast持續的時間(不傳參數默認了1.5s)。app
咱們怎麼將組件掛載到dom結構的呢?less
簡單來講就是用Vue.extend()建立一個子類,而後掛載到dom上。dom
<template>
<div class="toast" v-show="isNone">
<div >{{message}}</div>
</div>
</template>
<script>
export default {
data() {
return {
message: '默認信息',
isNone: false
}
},
methods: {
show(message='默認信息', duration = 1500) { //默認參數
this.message = message;
this.isNone = true;
setTimeout(() => { //用定時器實現彈窗出現時間
this.isNone = false;
this.message = '默認信息'
}, duration)
}
}
}
</script>
<style scoped>
.toast {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 10px 8px;
z-index: 999;
color: #fff;
background-color: rgba(0, 0, 0, .5);
border-radius: 10px;
}
</style>
複製代碼
結構很簡單,經過屬性isNone來動態控制Toast的出現和隱藏。函數
主要是show方法,當頁面調用show方法,第一個參數會賦值給message,第二個參數能夠決定Toast存在的時間(用定時器將isNone改成false)。ui
main.js
import Toast from './components/toast/index'
Vue.use(Toast) //安裝toast插件
複製代碼
看到這,首先咱們要了解Vue.use這api具體作了啥?
其實就是調用插件的install方法().
安裝 Vue.js 插件。若是插件是一個對象,必須提供 install 方法。若是插件是一個函數,它會被做爲 install 方法。install 方法調用時,會將 Vue 做爲參數傳入。
因此如今就要封裝install方法。
components/toast/index.js
import Toast from './Toast'
const obj = {} //對象
obj.install = function(Vue) { //封裝install方法
// 1. 建立組件構造器
const toastContrustor = Vue.extend(Toast)
// 2. new 組件實例
const toast = new toastContrustor();
// 3. 將組件實例, 掛載到某一個元素上
toast.$mount(document.createElement('div'))
// 4. toast.$el 對應的就是div
document.body.appendChild(toast.$el);
// 5. 添加到原型鏈上
Vue.prototype.$toast = toast
}
export default obj
複製代碼
const toastContrustor = Vue.extend(Toast)
先經過Vue.extend建立組件構造器。(install方法調用時,會將 Vue 做爲參數傳入)
使用基礎 Vue 構造器,建立一個「子類」。參數是一個包含組件選項的對象。
const toast = new toastContrustor();
經過new的方式 根據組件構造器建立出來一個組件實例。toast.$mount(document.createElement('div'))
將組件對象掛載到某一個元素上。document.body.appendChild(toast.$el);
將元素添加到body中。Vue.prototype.$toast = toast
將toast對象加入到Vue的原型鏈上,這樣在每一個頁面均可以用this.$toast操做。文章有錯誤的地方或者能夠改進的地方,歡迎各位大佬提提意見。
這是源代碼,若是本文對你有點幫助的話,不妨點個贊哦。