廣告網(wǎng)站設(shè)計(jì)公司好嗎做免費(fèi)推廣的平臺
提示:記錄工作中遇到的需求及解決辦法
文章目錄
- 前言
- 一、目錄結(jié)構(gòu)
- 二、代碼
- 1. 創(chuàng)建 m-Toast.vue 文件
- 2. 創(chuàng)建 global.js 文件
- 3. 在 main.js 文件中導(dǎo)入 global.js 文件
- 4. 在 App.vue 文件中使用 全局方法創(chuàng)建的 組件
前言
在此之前一直不明白Vue.extend( )干什么用的,如何使用,看了一些視頻,再結(jié)合vue文檔,淺淺的理解了一些,以及一些簡單的應(yīng)用,如有不對請指出。
我將使用腳手架生成一個vue2項(xiàng)目來解釋。
提示:以下是本篇文章正文內(nèi)容,下面案例可供參考
一、目錄結(jié)構(gòu)
二、代碼
1. 創(chuàng)建 m-Toast.vue 文件
<template><div class="message"><div class="text">{{ text }}</div></div>
</template>
<script>
export default {name: 'm-Toast',props: {text: {type: String,default: ''},},mounted () {this.timer = setTimeout(() => {this.$destroy()clearTimeout(this.timer);}, 2000)},destroyed () {clearTimeout(this.timer);document.body.removeChild(this.$el)},methods: {},
}
</script>
<style scoped>
.message {min-width: 380px;background-color: #f0f9eb;color: #67c23a;position: fixed;padding: 15px 15px 15px 20px;top: 20px;left: 50%;z-index: 2022;font-size: 14px;transform: translate(-50%, 0);
}.text {overflow: hidden;align-items: center;
}
</style>
2. 創(chuàng)建 global.js 文件
import Vue from "vue";
import Toast from "./components/m-Toast.vue";/** 創(chuàng)建 Toast對應(yīng)的Vue子類(構(gòu)造器)* 結(jié)合vue文檔 和 視頻,* extends 的參數(shù)可以通過導(dǎo)入一個寫好的組件* 或者 是函數(shù) ,例如: * {* template: '<div class="message">* <div class="text">{{ text }}</div>* </div>',* data: function () {* return {* text: '測試',* }* }* }* 下面我選擇通過導(dǎo)入組件的方法,因?yàn)榉奖闶褂脴邮?#xff0c;結(jié)構(gòu)更明了*/
let ToastSubclass = Vue.extend(Toast)// 全局掛載到原型上方便調(diào)用
Vue.prototype.$toast = function (text) {// 創(chuàng)建實(shí)例let ToastConstructor = new ToastSubclass({// 就是在調(diào)用組件的時候,給組件傳遞屬性值propsData: {text}});/** 掛載(渲染組件)* 使用 $mount() 但不傳掛載點(diǎn),返回一個完整的 Vue 組件實(shí)例*/ToastConstructor.$mount()// 把渲染后的真實(shí)DOM插入到BODY中即可document.body.appendChild(ToastConstructor.$el)
}
3. 在 main.js 文件中導(dǎo)入 global.js 文件
import Vue from 'vue'
import App from './App.vue'
// 導(dǎo)入 global.js 文件
import './global.js'Vue.config.productionTip = falsenew Vue({render: h => h(App),
}).$mount('#app')
4. 在 App.vue 文件中使用 全局方法創(chuàng)建的 組件
<template><div id="app"><button @click="config">按鈕</button></div>
</template><script>export default {name: 'App',data () {return {count: 0}},mounted () {},methods: {config () {this.$toast(`測試${this.count++}`)}}
}
</script><style></style>