本文提供了h5、小程序、apk/ios的伪全局挂载方法,可按需自取
一、h5挂载方法
1.globalCompMethods.js
const install = (Vue, vm) => {
const addH5component = function (url, name) {
return new Promise(async (r, _) => {
const idName = 'globalComp_' + new Date().getTime() + '_' + parseInt(Math.random() * 1000)
const customComponent = url.default
const globalComp = Vue.component(name, customComponent) // 创建组件
const globalCompNew = new globalComp() // 创建组件实例(可以传递参数 { propsData: props })
const DOM = document.createElement('div')
DOM.setAttribute('id', idName)
document.body.appendChild(DOM)
const comp = globalCompNew.$mount(DOM.appendChild(document.createElement('template'))) // 将虚拟dom节点改变成真实dom,获取组件的dom节点,并实现挂载
comp.componentId = idName
r(comp)
})
}
Vue.prototype.$showToast = async obj => {
// #ifdef H5
if (!vm.$refs.uToast) {
// 不同项目、版本u-toast位置不同
vm.$refs.uToast = await addH5component(require('@/uview-ui/components/u-toast/u-toast.vue'), 'uToast')
}
// #endif
vm.$refs.uToast.show(obj)
}
}
export default {
install,
}
2.main.js
import Vue from 'vue'
import App from './App'
const app = new Vue({ store, ...App })
// 全局组件方法
import globalCompMethods from '@/common/system/globalCompMethods.js'
Vue.use(globalCompMethods, app)
app.$mount()
3.随便在哪调用
mounted() {
this.$showToast({ title: '挂载成功', type: 'success', duration: 100000 })
},
二、小程序挂载方法
1.在终端初始化并安装插件
npm init
npm i vue-inset-loader
2.创建vue.config.js引入vue-inset-loader
const path = require('path')
module.exports = {
configureWebpack: {
module: {
rules: [{
test: /\.vue$/,
use: {
loader: path.resolve(__dirname, "./node_modules/vue-inset-loader")
},
}]
},
}
}
3.page.json中新增配置
1.全局配置
"insetLoader":{
"config":{
"uToast":"<u-toast ref='uToast'/>"
},
"label":["uToast"],
"rootEle":"view"
}
2.单页配置
"pages": [
{
"path": "pages/index/index", // 路由页面
"aliasPath":"/", //对于h5端你必须在首页加上aliasPath并设置为/
"name": "index",
//单独配置,用法跟全局配置一致,优先级高于全局
"label": ["uToast"],
"rootEle": "view"
},
]
4.创建globalCompMethods.js文件
const install = (Vue, vm) => {
Vue.prototype.$showToast = async obj => {
vm.$refs.uToast.show(obj)
}
}
export default {
install,
}
5.main.js中
import Vue from 'vue'
import App from './App'
const app = new Vue({ store, ...App })
// 全局组件方法
import globalCompMethods from '@/common/system/globalCompMethods.js'
Vue.use(globalCompMethods, app)
app.$mount()
6.随便在哪调用
mounted() {
this.$showToast({ title: '挂载成功', type: 'success', duration: 100000 })
},
三、apk/ios挂载方法(伪全局)
1.App.vue
globalData: {
toast:Object,
},
2.navbar组件
<template>
<view>
<u-toast ref="uToast" />
</view>
</template>
<script>
export default {
mounted(){
getApp().globalData.showToast = this.$refs.uToast.show
}
}
</script>
3.在有navbar组件的页面使用
getApp().globalData.showToast({
title: res.message,
type: 'success',
})