在components目录下新建 Tips文件夹作为 Tips 组件文件,新建 index.vue 和 index.js 文件进行组件封装,并在 main.js 中将组件挂载到vue原型上实现全局使用(只使用一次 可在request.js引用)

components/Tips/index.vue:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<template>
<view ref="tips" v-show="show" class="tips uni-mask">
<view class="tips-content">
<u-image class="tips-img" :src="srcs[type]" />
<u-icon class="tips-close" name="close-circle" size="52" color="#b9b9b9" @click="close" />
</view>
</view>
</template>

<script>
export default {
name:"Tips",
data() {
return {
show: true,
type: 'free',
srcs: {
free: '/static/img/free.png',
vip: '/static/img/vip.png'
}
};
},
methods: {
close() {
this.show = false;
document.body.removeChild(this.$refs['pageTip'].$el); //父元素中移除dom元素($el为组件实例)
this.$destroy(true) //销毁组件
}
}
}
</script>

<style lang="scss">
.tips {
.tips-content {
width: 518rpx;
height: 974rpx;
text-align: center;
}
.tips-img {
width: 259px;
height: 450px;
}
.tips-close {
margin-top: 22px;
}
}
</style>

components/Tips/index.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import Vue from 'vue'
import tips from './index.vue'

//创建Toast构造器
let TipsConstructor = Vue.extend(tips)
let instance

const Tips = function(options = {}) {
//设置默认参数为对象,如果参数为字符串,参数中message属性等于该参数
if(typeof options === 'string') {
options = {
message: options
}
}
//创建实例
instance = new TipsConstructor({
data: options
})
//将实例挂载到body下
document.body.appendChild(instance.$mount().$el)
}

// 导出处理
export default Tips

1.全局使用- main.js:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import Vue from 'vue'
import App from './App.vue'
import router from './router'

//引入Toast组件
import Tips from './components/Tips'

Vue.config.productionTip = false

//将Tips组件挂载到vue原型上
Vue.prototype.$tips = tips

new Vue({
router,
render: h => h(App),
}).$mount('#app')

在需要使用 Tips 组件的地方调用 并传入参数使用

1
2
//全局使用时
this.$tips({ type: 'free' })

2.局部使用-request.js

1
import Tips from "@/components/Tips/index.js";

在需要使用 Tips 组件的地方调用 并传入参数使用

1
Tips({   type: 'free'  });