微信小程序引用自定义函数的几种方法

您所在的位置:网站首页 建立javascript自定义函数并调用 微信小程序引用自定义函数的几种方法

微信小程序引用自定义函数的几种方法

2024-01-22 05:59| 来源: 网络整理| 查看: 265

微信小程序有时需要函数里面调用函数,然而,使用不当经常报错误

thirdScriptError Cannot read property ‘testaaa’ of undefined;at api request success callback function TypeError: Cannot read property ‘testaaa’ of undefined

总结了一下,列出几种调用函数的方法:

引用同一js文件中的方法函数 testaaa: function (info) { console.log(info); }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { wx.request({ url: 'http://127.0.0.1:5000/', data: '', header: {}, method: 'GET', dataType: 'json', responseType: 'text', success: this.testaaa("fdgdfg"), fail: function(res) {}, complete: function(res) {}, }) }, 函数里面调用函数 testaaa: function (info) { console.log(info); }, /** * 生命周期函数--监听页面加载 */ onLoad: function (options) { var that = this; wx.request({ url: 'http://127.0.0.1:5000/', data: '', header: {}, method: 'GET', dataType: 'json', responseType: 'text', success: function (res) { that.testaaa("fdgdfg")}, fail: function(res) {}, complete: function(res) {}, }) }, 调用不同文件的函数

在自定义的文件中定义方法,然后在需要使用的文件中调用。 如在index.js文件中定义,然后在xxx.js中使用。 那么index.js中定义的方法,需要通过module.exports={xxxMethord: xxxMethord}公开暴露出来 否则被调用时识别不出来会出现;同时,在xxx.js文件中使用时,需要通过require(“路径/util.js”)导入util.js文件,再进行调用。

index.js中定义 (不是写在Page({})里)

module.exports = { openfile: openfile } function openfile(info) { console.log("打开文件"); }

xxx.js 中引用:

Page({ testaaa: function (info) { var index = require('../index/index.js') index.openfile() }, }) 调用App.js的函数

在app.js文件里定义一个函数,然后在被使用的文件中调用,如下代码示例:

app.js:

App({ Gettime: function(info) { console.log("我是一个在App里定义的函数"); }, })

xxx.js中引用:

const app = getApp() Page({ testaaa: function () { app.Gettime(); } })


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3