首次提交

This commit is contained in:
2026-08-20 18:29:49 +08:00
commit 76827aedfe
77 changed files with 24937 additions and 0 deletions
+14
View File
@@ -0,0 +1,14 @@
## 1.0.62023-04-12
为防冲突,给selectComponent两个函数添加前缀zp
## 1.0.52023-03-28
修复ts项目找不到setData的问题
## 1.0.42023-03-07
修复小程序报错
## 1.0.32023-02-26
修复pageLifetimes
## 1.0.22023-01-06
增加使用文档
## 1.0.12022-12-07
更新文档
## 1.0.02022-12-07
init
+52
View File
@@ -0,0 +1,52 @@
//lifetimes
import { pageLifetimes } from './lifecycle/pageLifetimes';
//methods
import { clone } from './methods/clone';
import { handleDataset } from './methods/dataset';
import { escape2Html, html2Escape } from './methods/escape';
import { parseEventDynamicCode } from './methods/event';
import { getTabBar } from './methods/getTabBar';
import { getRelationNodes } from './methods/relation';
import { selectComponent as zpSelectComponent,
selectAllComponents as zpSelectAllComponents } from './methods/selectComponent';
import { setData } from './methods/setData';
export default {
// #ifndef VUE3
install(Vue, option) {
Vue.mixin({
...pageLifetimes,
methods: {
clone,
handleDataset,
escape2Html,
html2Escape,
parseEventDynamicCode,
getTabBar,
getRelationNodes,
zpSelectComponent,
zpSelectAllComponents,
setData
}
})
}
// #endif
// #ifdef VUE3
...pageLifetimes,
methods: {
clone,
handleDataset,
escape2Html,
html2Escape,
parseEventDynamicCode,
getTabBar,
getRelationNodes,
zpSelectComponent,
zpSelectAllComponents,
setData
}
// #endif
}
+31
View File
@@ -0,0 +1,31 @@
import Vue from 'vue';
//lifetimes
import { pageLifetimes } from './lifecycle/pageLifetimes';
//methods
import { clone } from './methods/clone';
import { handleDataset } from './methods/dataset';
import { escape2Html, html2Escape } from './methods/escape';
import { parseEventDynamicCode } from './methods/event';
import { getTabBar } from './methods/getTabBar';
import { getRelationNodes } from './methods/relation';
import { selectComponent as zpSelectComponent, selectAllComponents as zpSelectAllComponents } from './methods/selectComponent';
import { setData } from './methods/setData';
// console.log("lifecycle", lifecycle)
export default Vue.extend({
...pageLifetimes,
methods: {
clone,
handleDataset,
escape2Html,
html2Escape,
parseEventDynamicCode,
getTabBar,
getRelationNodes,
zpSelectComponent,
zpSelectAllComponents,
setData
}
});
+2
View File
@@ -0,0 +1,2 @@
export * from './pageLifetimes'
@@ -0,0 +1,39 @@
/**
* 组件pageLifetimes处理,需在页面生命周期里调用
* @param {Object} node
* @param {Object} lifeName
*/
function handlePageLifetime(node, lifeName) {
node.$children.map(child => {
if (typeof child[lifeName] == 'function') child[lifeName]()
handlePageLifetime(child, lifeName)
})
}
export const pageLifetimes = {
onLoad() {
// uni.onWindowResize(CALLBACK) 监听窗口尺寸变化事件
// 平台差异说明
// App H5 微信小程序 支付宝小程序 百度小程序 抖音小程序 飞书小程序 QQ小程序
// √ √ √ x x x √ √
// #ifdef H5 || MP-LARK || MP-QQ
uni.onWindowResize((res) => {
handlePageLifetime(this, "handlePageResize")
})
// #endif
},
onShow() {
handlePageLifetime(this, "handlePageShow")
},
onHide() {
handlePageLifetime(this, "handlePageHide")
},
onResize() {
//onResize 监听窗口尺寸变化 App、微信小程序、快手小程序
// #ifdef APP || MP-WEIXIN || MP-KUAISHOU
handlePageLifetime(this, "handlePageResize")
// #endif
}
};
+10
View File
@@ -0,0 +1,10 @@
/**
* 用于处理对props进行赋值的情况
* //简单处理一下就行了
*
* @param {*} target
* @returns
*/
export function clone(target) {
return JSON.parse(JSON.stringify(target))
}
+21
View File
@@ -0,0 +1,21 @@
/**
* 用于处理dataset
* 自定义组件的事件里,是获取不到e.currentTarget.dataset的
* 因此收集data-参数,手动传进去
*
* @param {*} event
* @param {*} dataSet
*/
export function handleDataset(event, dataSet = {}) {
if (event && !event.currentTarget) {
if (dataSet.tagId) {
event.currentTarget = {
id: dataSet.tagId
}
} else {
event.currentTarget = {
dataset: dataSet
}
}
}
}
+36
View File
@@ -0,0 +1,36 @@
/**
* 转义符换成普通字符
* @param {*} str
* @returns
*/
export function escape2Html(str) {
if (!str) return str
var arrEntities = {
'lt': '<',
'gt': '>',
'nbsp': ' ',
'amp': '&',
'quot': '"'
}
return str.replace(/&(lt|gt|nbsp|amp|quot);/ig, function(all, t) {
return arrEntities[t]
})
}
/**
* 普通字符转换成转义符
* @param {*} sHtml
* @returns
*/
export function html2Escape(sHtml) {
if (!sHtml) return sHtml
return sHtml.replace(/[<>&"]/g, function(c) {
return {
'<': '&lt;',
'>': '&gt;',
'&': '&amp;',
'"': '&quot;'
} [c]
})
}
+10
View File
@@ -0,0 +1,10 @@
/**
* 解析事件里的动态函数名,这种没有()的函数名,在uniapp不被执行
* 比如:<view bindtap="{{openId==undefined?'denglu':'hy_to'}}">立即</view>
* @param {*} exp
*/
export function parseEventDynamicCode(e, exp) {
if (typeof(this[exp]) === 'function') {
this[exp](e)
}
}
@@ -0,0 +1,19 @@
/**
* 接管getTabBar函数,默认uni-app是没有这个函数的
* 适用于使用custom-tab-bar自定义导航栏的小程序项目
* 需注意:
* 1.custom-tab-bar下面仍是小程序文件
* 2.pages.json里面需使用条件编译区分好小程序和非小程序的tabBar配置
*/
export function getTabBar() {
return {
setData(obj) {
if (typeof this.$mp?.page?.getTabBar === 'function' &&
this.$mp?.page?.getTabBar()) {
this.$mp.page.getTabBar().setData(obj)
} else {
console.log("当前平台不支持getTabBar(),已稍作处理,详细请参见相关文档。")
}
}
}
}
+8
View File
@@ -0,0 +1,8 @@
export * from './clone'
export * from './dataset'
export * from './escape'
export * from './event'
export * from './getTabBar'
export * from './relation'
export * from './selectComponent'
export * from './setData'
+10
View File
@@ -0,0 +1,10 @@
/**
* 组件间关系
* 注意:须与p-f-unicom配合使用!!!
* @param {*} name
* @returns
*/
export function getRelationNodes(name) {
if(!this.$unicom) throw "this.getRelationNodes()需与p-f-unicom配合使用!"
return this.$unicom('@' + name)
}
@@ -0,0 +1,196 @@
const createTraverse = () => {
let stop = false;
return function traverse(root, callback) {
if (!stop && typeof callback === 'function') {
let children = root.$children;
for (let index = 0; !stop && index < children.length; index++) {
let element = children[index];
stop = callback(element) === true;
traverse(element, callback);
}
}
};
};
/**
* 安全的JSON.stringify
* @param {Object} node
*/
function safeStringify(node) {
var cache = [];
var str = JSON.stringify(node, function(key, value) {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// 移除
return;
}
// 收集所有的值
cache.push(value);
}
return value;
});
cache = null; // 清空变量,便于垃圾回收机制回收
return str
}
const match = (node, selector) => {
var vnode = node._vnode;
//好家伙,在微信小程序里,node里面根本找不到class,因此这种方式没法搞了
//关键之处!
// console.log("attrs", (vnode.context.$vnode.data));
vnode = vnode?.context?.$vnode ?? ""
//console.log(vnode.data) --> [Object] {"staticClass":"bar","attrs":{"_i":0}} at selectComponent.js:72
if (!vnode || !vnode.data) {
return false
}
let attrs = vnode.data.attrs || {};
let staticClass = vnode.data.staticClass || '';
const id = attrs.id || '';
if (selector[0] === '#') {
return selector.substr(1) === id;
} else {
staticClass = staticClass.trim().split(' ');
selector = selector.substr(1).split('.');
return selector.reduce((a, c) => a && staticClass.includes(c), true);
}
};
const selectorBuilder = (selector) => {
selector = selector.replace(/>>>/g, '>');
selector = selector.split('>').map(s => {
return s.trim().split(' ').join(`').descendant('`);
}).join(`').child('`);
// 替换掉new Function方式,因为小程序不支持new Function和eval
//return new Function('Selector', 'node', 'all', `return new Selector(node, all).descendant('` + selector + `')`);
return function(Selector, node, all) {
return new Selector(node, all).descendant(selector)
}
};
class Selector {
constructor(node, all = false) {
this.nodes = [node];
this.all = all;
}
child(selector) {
let matches = [];
if (this.all) {
this.nodes.forEach(node => {
matches.push(...node.$children.filter(node => match(node, selector)));
});
} else {
if (this.nodes.length > 0) {
let node = this.nodes[0].$children.find(node => match(node, selector));
matches = node ? [node] : [];
}
}
this.nodes = matches;
return this;
}
descendant(selector) {
let matches = [];
this.nodes.forEach(root => {
createTraverse()(root, (node) => {
if (match(node, selector)) {
matches.push(node);
return !this.all;
}
});
});
this.nodes = matches;
return this;
}
}
////////////////////////////////////////////selectComponent//////////////////////////////////////////////////
/**
* 其他平台,如APP
* @param {Object} selector
*/
function selectComponentOther(selector) {
const selectors = selector.split(',').map(s => s.trim());
if (!selectors[0]) {
return null;
}
const querySelector = selectorBuilder(selectors[0]);
return querySelector(Selector, this, false, selector).nodes[0];
}
/**
* 还是用这个微信小程序的实现吧
* @param {Object} selector
*/
var selectComponentWeiXin2 = function(selector) {
console.log(".$scope",this.$scope.selectComponent(selector))
return this.$scope.selectComponent(selector)?.data || undefined
}
/**
* selectComponent
* @param {Object} args
*/
export function selectComponent(args) {
// console.log(".$scope",this.$scope)
// #ifdef MP
//H5和小程序能正常使用这个函数
//重写selectComponent函数,因为默认会多一层$vm
return selectComponentWeiXin2.call(this, args)
// #endif
// #ifndef MP
// 因App的结构略有差异,此函数无法正常使用
// function(e){return function e(t,n){if(n(t.$vnode||t._vnode))return t;for(var r=t.$children,i=0;i<r.length;i++){var o=e(r[i],n);if(o)return o}}(this,ov(e))}
// return selectComponentOther(args)
return selectComponentOther.call(this, args)
// #endif
}
////////////////////////////////////////////selectAllComponents//////////////////////////////////////////////////
/**
* 其他平台,如APP
* @param {Object} selector
*/
function selectAllComponentsOther(selector) {
const selectors = selector.split(',').map(s => s.trim());
let selected = [];
selectors.forEach(selector => {
const querySelector = selectorBuilder(selector);
selected = selected.concat(querySelector(Selector, this, true, selector).nodes);
});
return selected;
}
/**
* 还是用这个微信小程序的实现吧
* @param {Object} selector
*/
var selectAllComponentsWeiXin2 = function(selector) {
var list = this.$scope.selectAllComponents(selector) || []
list = list.map(item => item.data)
return list
}
/**
* selectAllComponents
* @param {Object} args
*/
export function selectAllComponents(args) {
// #ifdef MP
//H5和小程序能正常使用这个函数
//重写selectComponent函数,因为默认会多一层$vm
return selectAllComponentsWeiXin2.call(this, args)
// #endif
// #ifndef MP
// 因App的结构略有差异,此函数无法正常使用
return selectAllComponentsOther.call(this, args)
// #endif
}
+90
View File
@@ -0,0 +1,90 @@
import _set from '../utils/_set'
import debounce from '../utils/debounce'
/**
* 老setData polyfill
* 用于转换后的uniapp的项目能直接使用this.setData()函数
* @param {*} obj
* @param {*} callback
*/
function oldSetData (obj, callback) {
let that = this
const handleData = (tepData, tepKey, afterKey) => {
var tepData2 = tepData
tepKey = tepKey.split('.')
tepKey.forEach(item => {
if (tepData[item] === null || tepData[item] === undefined) {
let reg = /^[0-9]+$/
tepData[item] = reg.test(afterKey) ? [] : {}
tepData2 = tepData[item]
} else {
tepData2 = tepData[item]
}
})
return tepData2
}
const isFn = function (value) {
return typeof value == 'function' || false
}
Object.keys(obj).forEach(function (key) {
let val = obj[key]
key = key.replace(/\]/g, '').replace(/\[/g, '.')
let front, after
let index_after = key.lastIndexOf('.')
if (index_after != -1) {
after = key.slice(index_after + 1)
front = handleData(that, key.slice(0, index_after), after)
} else {
after = key
front = that
}
if (front.$data && front.$data[after] === undefined) {
Object.defineProperty(front, after, {
get () {
return front.$data[after]
},
set (newValue) {
front.$data[after] = newValue
that.hasOwnProperty("$forceUpdate") && that.$forceUpdate()
},
enumerable: true,
configurable: true
})
front[after] = val
} else {
that.$set(front, after, val)
}
})
// this.$forceUpdate();
isFn(callback) && this.$nextTick(callback)
}
/**
* 变量名正则
*/
const variableNameReg = /^([^\x00-\xff]|[a-zA-Z_$])([^\x00-\xff]|[a-zA-Z0-9_$])*$/
/**
* 2022-10-31 重写setData
* 2023-05-08 增加微信“简易双向绑定”支持
* 用于转换后的uniapp的项目能直接使用this.setData()函数
* @param {Object} obj
* @param {Object} callback
*/
export function setData (obj, callback = null) {
Object.keys(obj).forEach((key) => {
_set(this, key, obj[key])
//处理微信“简易双向绑定”
if (variableNameReg.test(key) && key.endsWith("Clone")) {
let propName = key.replace(/Clone$/, "")
if (this.$options && this.$options.propsData[propName]) {
this.$emit(`update:${propName}`, obj[key])
}
}
})
this.$forceUpdate();
if (typeof callback == 'function') this.$nextTick(callback)
}
+86
View File
@@ -0,0 +1,86 @@
{
"id": "zp-mixins",
"displayName": "zp-mixins",
"version": "1.0.6",
"description": "用于minipropgram-to-uniapp的mixins",
"keywords": [
"mixins",
"小程序",
"代码转换"
],
"repository": "https://github.com/zhangdaren/zp-mixins",
"engines": {
"HBuilderX": "^3.1.0"
},
"dcloudext": {
"type": "sdk-js",
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "无",
"data": "无",
"permissions": "无"
},
"npmurl": ""
},
"uni_modules": {
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "y",
"aliyun": "y"
},
"client": {
"Vue": {
"vue2": "y",
"vue3": "y"
},
"App": {
"app-vue": "y",
"app-nvue": "n"
},
"H5-mobile": {
"Safari": "y",
"Android Browser": "y",
"微信浏览器(Android)": "y",
"QQ浏览器(Android)": "y"
},
"H5-pc": {
"Chrome": "y",
"IE": "y",
"Edge": "y",
"Firefox": "y",
"Safari": "y"
},
"小程序": {
"微信": "y",
"阿里": "y",
"百度": "y",
"字节跳动": "y",
"QQ": "y",
"钉钉": "y",
"快手": "y",
"飞书": "y",
"京东": "y"
},
"快应用": {
"华为": "y",
"联盟": "y"
}
}
}
},
"dependencies": {
"tern": "^0.24.3"
}
}
+107
View File
@@ -0,0 +1,107 @@
# zp-mixins
本插件,基本无法单独使用。
为方便miniprogram-to-uniapp(小程序转uniapp项目)工具后续升级,特单独摘出做成插件,便于后续更新。
注意:
1.本插件仅限于miniprogram-to-uniapp(小程序转uni-app项目)转换工具使用,
2.如果是新项目或uni-app项目,建议还是使用vue/uni-app它自身支持的方式实现,效率更高些。
3.目前仅支持vue2/vue3的options写法。至于setup,因其天生弱化mixin,也无this,建议直接import导入按需使用吧~
# 安装
点击右侧 “使用 HBuilderX 导入插件” 按钮,并选择对应项目。
# 使用
在main.js文件里面增加引用,即可全局使用这些函数,如下所示:
```
import App from './App'
// 添加zpMixins
import zpMixins from '@/uni_modules/zp-mixins/index.js'
// #ifndef VUE3
import Vue from 'vue'
Vue.use(zpMixins)
Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
...App
})
app.$mount()
// #endif
// #ifdef VUE3
import { createSSRApp } from 'vue'
export function createApp() {
const app = createSSRApp(App)
app.mixin(zpMixins)
return {
app
}
}
// #endif
```
注意:vue3项目仅支持Options API方式(setup API写法有点不同,不支持这种方式使用,建议直接通过import引入使用)。
# 功能介绍
## pageLifetimes(组件所在页面的生命周期)
处理组件里的pageLifetimes
## clone(深拷贝)
深拷贝的简单版本,未处理循环引用。
## handleDataset
用于处理dataset
在自定义组件的事件里,是获取不到e.currentTarget.dataset的
因此收集data-参数,手动传进去
## html2Escape 普通字符转换成转义符
用于替换wxParse为mp-html时使用
## escape2Html 转义符换成普通字符
暂未用上
## parseEventDynamicCode
解析事件里的动态函数名,这种没有()的函数名,在uniapp不被执行
比如:<view bindtap="{{openId==undefined?'denglu':'hy_to'}}">立即</view>
## getTabBar
实现小程序自定义组件的this.getTabBar().setData()函数
## getRelationNodes
获取组件间关系this.getRelationNodes()
注意:
1.须与p-f-unicom配合使用!
2.并不能与小程序的getRelationNodes相提并论,因为底层实现不一样
## selectComponent
## selectAllComponents
抹平各平台差异,实现类似于小程序的selectComponent和selectAllComponents函数。
使用方式与小程序一致。
注:新项目建议还是使用ref这种方式,获取组件实例。
## setData
1.实现setData函数,让uni-app也能支持使用setData函数。
2.实现微信“简易双向绑定”
注意:本函数仅为小程序转换uniapp项目所作的支撑,如uni-app项目里,最好还是使用this.xx这种方式。
+26
View File
@@ -0,0 +1,26 @@
/**
* lodash set
* @param {*} obj
* @param {*} path
* @param {*} value
* @returns
*/
function _set(obj, path, value) {
if (Object(obj) !== obj) return obj // When obj is not an object
// If not yet an array, get the keys from the string-path
if (!Array.isArray(path)) path = path.toString().match(/[^.[\]]+/g) || []
path.slice(0, -1).reduce((a, c, i) => // Iterate all of them except the last one
Object(a[c]) === a[c] // Does the key exist and is its value an object?
// Yes: then follow that path
?
a[c]
// No: create the key. Is the next key a potential array-index?
:
a[c] = Math.abs(path[i + 1]) >> 0 === +path[i + 1] ? [] // Yes: assign a new array object
:
{}, // No: assign a new plain object
obj)[path[path.length - 1]] = value // Finally assign the value to the last key
return obj // Return the top-level object to allow chaining
}
export default _set
+17
View File
@@ -0,0 +1,17 @@
/**
* 防抖
* @param {Object} scope //引用的this,发现不显式传this,拿不到。
* @param {Object} fn
* @param {Object} delay
*/
let t = null
const debounce = function(scope, fn, delay) {
if (t !== null) {
clearTimeout(t)
}
t = setTimeout(() => {
scope[fn]()
}, delay)
}
export default debounce