微信小程序微信小程序开发小程序

小程序js模块化

2018-11-10  本文已影响3人  前端来入坑

在.js后缀文件中写下json格式的数据或者写下方法,然后通过module.exports={}导出,在需要的地方var tools = requice('../../tools.js'),通过tools.导出的name就可以使用了.当然还可以用import {...} from '../../tools.js'的形式按需导入。

举个栗子.jpg

外部导入数据形式

//tools.js
var studentList = [
    {
        name: "LLL",
        age: "18",
        hobby: "sleep"
    },
    {
        name: "XXX",
        age: "22",
        hobby: {
            one: "eat",
            two: "sleep"
        }
 
    }
]
 
//模块化导出
module.exports = {
    studentList: studentList
}

在需要用到以上数据的js文件中引入

//index.js
var tools = require("../../tools.js")
//获取应用实例
var app = getApp()
Page({
  data: {
  },
  onLoad: function () {
    this.setData({
        studentList:tools.studentList
        });
  }
})

外部导入方法的形式,其实也是一样的,也举个栗子

 // tools.js
 function sayHello(name) {
   console.log(`Hello ${name} !`)
 }
 function sayGoodbye(name) {
   console.log(`Goodbye ${name} !`)
 }
//有多种导出写法,这里只写这一种
module.exports = {
    sayHello:sayHello,
    sayGoodbye:sayGoodbye
}

在需要用到以上数据的js文件中引入

var tools = require("../../tools.js")
 Page({
  sayhello: function() {
     tools.sayHello('LLL')
  },
  saygoodbye: function() {
     tools.sayGoodbye('XXX')
  }
})

导入封装的方法并实例化之后使用

export class bigFun{
  myfun(a,b) {
    let c = a +' ' +b;
    return c;
  }
}
import { myFun } from "../../tools.js";//按需调用,当然目前里面也只有一个myfun方法

const tools = new bigFun();//new实例化

Page({
  data: {
  },
  onLoad: function () {
     let name = tools.myfun('LLL','XXX');//传入参数调用函数
     console.log(name);
  }
})
上一篇 下一篇

猜你喜欢

热点阅读