本次封裝的組件以toast組件為例
以前使用移動(dòng)端ui插件時(shí),通過(guò)一句代碼比如 $.toast( ‘ 需要顯示的內(nèi)容 ' ),從而在頁(yè)面上展示這段文字,并在一定時(shí)間后消失。
現(xiàn)在我們也嘗試自己封裝toast組件。
準(zhǔn)備工作:vue-cli腳手架工程
先看一下涉及到的文件目錄截圖:
這次的封裝主要涉及的文件是Toast.vue toast.js Hello.vue,主要思路如下:
① Toast.vue是我們要使用的toast組件;
② toast.js里面用Vue.extend()擴(kuò)展一個(gè)組件構(gòu)造器,然后通過(guò)實(shí)例化組件構(gòu)造器,就可創(chuàng)造出可復(fù)用的組件。
最后在toast.js里面導(dǎo)出函數(shù)myToast,函數(shù)myToast里面的邏輯在代碼里面有解釋;
③ Hello.vue里調(diào)用函數(shù),顯示組件。
Toast.vue代碼:
<template> <div class="toast" v-if="isShow"> <div class="toast-div">{{ text }}</div> </div> </template> <script> export default{ data(){ return { text:'內(nèi)容', isShow:true, duration:1500 } } } </script> <style> *{ margin: 0; padding: 0; } .toast{ position: fixed; left: 50%; transform: translate(-50%, 0); margin-top: 5rem; background: #000000; line-height: 0.7rem; color: #FFFFFF; padding: 0 0.2rem; border-radius: 0.2rem; } </style>
Toast.js代碼:
import Vue from 'vue'; import Toast from '@/components/Toast'; //引入組件 let ToastConstructor = Vue.extend(Toast) // 返回一個(gè)“擴(kuò)展實(shí)例構(gòu)造器” let myToast = ()=>{ let toastDom = new ToastConstructor({ el:document.createElement('div') //將toast組件掛載到新創(chuàng)建的div上 }) document.body.appendChild( toastDom.$el ) //把toast組件的dom添加到body里 } export default myToast;
Hello.vue代碼:
<template> <div class="hello"> <button @click="showToast">按鈕</button> </div> </template> <script> import Vue from 'vue'; import toast from './js/toast'; //引入toast函數(shù) Vue.prototype.$toast = toast; //給Vue對(duì)象添加$toast方法 export default { name: 'hello', data () { return { } }, methods:{ showToast(){ this.$toast(); //現(xiàn)在就可以調(diào)用了 } } } </script>
通過(guò)以上步驟,離真正的toast效果還是有區(qū)別的,我們要達(dá)到的效果是讓顯示的內(nèi)容在一段時(shí)間后消失,那么,得從toast.js里面修改,得重新寫myToast函數(shù),給他設(shè)置兩個(gè)傳入?yún)?shù),一個(gè)是顯示的內(nèi)容,一個(gè)是顯示的時(shí)間。
toast.js修改后的代碼如下:
import Vue from 'vue'; import Toast from '@/components/Toast'; //引入組件 let ToastConstructor = Vue.extend(Toast) // 返回一個(gè)“擴(kuò)展實(shí)例構(gòu)造器” let myToast = (text,duration)=>{ let toastDom = new ToastConstructor({ el:document.createElement('div') //將toast組件掛載到新創(chuàng)建的div上 }) document.body.appendChild( toastDom.$el ) //把toast組件的dom添加到body里 toastDom.text = text; toastDom.duration = duration; // 在指定 duration 之后讓 toast消失 setTimeout(()=>{ toastDom.isShow = false; }, toastDom.duration); } export default myToast;
那么,現(xiàn)在我們?cè)贖ello.vue中調(diào)用的時(shí)候就應(yīng)該是這樣了:this.$toast('新內(nèi)容',2000);我們的組toast組件可以正常使用了!
以上這篇在vue中封裝可復(fù)用的組件方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
聲明:本網(wǎng)頁(yè)內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問(wèn)題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com