UniApp转微信小程序之全局组件

本文详细介绍了如何在UniApp和微信小程序中设置全局组件,包括Vue自带的component方法、easycom的自动扫描和自定义注册,以及微信小程序中使用vue-inset-loader进行全局组件插入的步骤和配置。
摘要由CSDN通过智能技术生成

一、UniApp设置全局组件

1.全局注册组件

两种方法推荐使用easycom 注册,easycom可以大规模注册组件

//方法一 Vue自带component方法  
//位置 main.js

import GlobalComponent from './components/index.vue'
Vue.component("GlobalComponent",GlobalComponent)

//方法二 使用easycom 
//位置 pages.json
{

 "easycom": {
		"autoscan": true,
		"custom": {
            "^mt-(.*)": "@/components/blog/mt-$1.vue",
			"GlobalComponent": "@/components/index.vue"

		}
	},
}

2.全局插入组件

//位置 main.js
import GlobalComponents from './components/index.vue'
const ComponentsObj = Vue.extend(GlobalComponents)


// h5所有页面挂上GlobalComponents组件
const initGlobalComponents = () => {

	//不兼容移动端
	const uniApp = app?.$el
	
	//在H5端为uni-app结点,在微信小程序中为null直接返回
	//console.log(uniApp)
	
	if (!uniApp) return
     
	// 全局组件挂载
	const vm = new ComponentsObj({
		store,
	}).$mount()

	uniApp?.appendChild(vm?.$el)
}

//在App挂载后操作
initGlobalComponents()

二、微信小程序设置全局组件

1.下载插件

npm i vue-inset-loader

2.配置vue.config.js文件

没有这个文件的话,新建一个vue.config.js文件


const path = require('path')

module.exports = {
	configureWebpack: {
		module: {
			rules: [{
				test: /\.vue$/,
				use: {
					loader: path.resolve(__dirname, "./node_modules/vue-inset-loader")
				},
			}]
		},
	}
}

3.注册全局组件

和uniapp中注册全局组件操作一样

4.配置pages.json文件

//在pages.json文件中新加insetLoader属性
	"insetLoader": {
		//配置
		"config": {
			"GlobalComponent": "<GlobalComponent/>"
		},
		// 全局配置  
		//需要挂在的组件名
		"label": ["GlobalComponent"],
		//根元素的标签类型 
		"rootEle": ".*"
	},

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值