微信小程序使用export和import

小程序支持模块化开发,可以将一些公共的代码抽离成为一个单独的 js 文件,作为一个模块。模块只有通过 module.exports 或者 exports 才能对外暴露接口。引入模块通过require方式。

创建模块

function sayHello(name) {
  console.log(`Hello ${name} !`)
}
function sayGoodbye(name) {
  console.log(`Goodbye ${name} !`)
}

module.exports.sayHello = sayHello
exports.sayGoodbye = sayGoodbye

引入模块

var common = require('common.js')
Page({
  helloMINA: function() {
    common.sayHello('MINA')
  },
  goodbyeMINA: function() {
    common.sayGoodbye('MINA')
  }
})

这是官方提供的方法,我个人还是比较喜欢使用export和import,使用起来比较顺手,可能是因为我一直用Vue开发的原因,下面拿一个实际例子,讲一讲export和import。

最近在开发的一个小程序项目,打算使用Promise对API这块做下封装,统一管理API请求。

新建request.js,提取公共请求路径

// 公共路径
const path = "http://172.16.50.83:82"

定义promise化接口

/**
 * promise化接口
 */
function wxRequest(url, method, params) {
  return new Promise((resolve, reject) => {
    wx.request({
      url: path + url,
      method: method,
      data: params,
      header: {
        'content-type': 'application/json'
      },
      success: res => resolve(res),
      fail: res => reject(res)
    })
  });
}

登录接口

function login(params = {}) {
  return wxRequest('/wechatuser', 'post', params);
}

导出

// 导出
module.exports = {
  login
}

上面这些代码都在一个文件中,完整代码就不展示了。

接下来就是导入新建接口文件,

import {login} from '../../api/request'

调用

login().then(res=>{
  console.log(res)
})

注意一点的是,在引入模块时,要使用相对路径,如果使用绝对路径,在编译后会导致文件找不到。

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Element是一套基于Vue.js的UI组件库,在微信小程序使用Element需要进行一定的适配工作。 具体步骤如下: 1. 安装element-ui 使用npm安装element-ui: ``` npm install element-ui --save ``` 2. 配置webpack 在webpack配置文件中添加以下代码: ``` resolve: { alias: { 'element-ui': 'element-ui/lib/index.js' } }, module: { rules: [ { test: /\.vue$/, loader: 'mpvue-loader', options: { checkMPEntry: true } }, { test: /\.js$/, loader: 'babel-loader', include: [ path.resolve(__dirname, '../src'), path.resolve(__dirname, '../node_modules/element-ui/src'), path.resolve(__dirname, '../node_modules/element-ui/packages') ] } ] } ``` 3. 适配element-ui组件 由于微信小程序不支持使用Vue.js的template模板语法,需要将element-ui组件适配为小程序支持的wxml模板语法。 具体步骤为: - 将el-前缀的组件改为使用van-前缀的组件,例如el-button改为van-button。 - 修改组件的属性和事件。例如,el-button的@click事件改为bindtap,el-button的size属性改为size和plain属性的值为Boolean类型。 4. 引入element-ui组件 在需要使用element-ui组件的页面中,引入对应的组件即可: ``` <template> <div class="container"> <van-button>按钮</van-button> <van-dialog :visible.sync="dialogVisible">对话框</van-dialog> </div> </template> <script> import { Button, Dialog } from 'element-ui' export default { components: { VanButton: Button, VanDialog: Dialog }, data() { return { dialogVisible: false } } } </script> ``` 以上就是在微信小程序使用element-ui的基本步骤。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值