weex-怎么定义全局方法

博主是做iOS的,所以定义全局方法的是很了解了,有很多种方法吧可以来做,比如,扩展,单例,pch等,但是关于weex怎么来做一个全局的方法来方便引入呢?下面就来进行说明:
1.建立你的weex项目,这个不用多说了吧,实在不会的,去weex官网看吧;
2.新建一个js文件:
我们叫function.js吧,然后在里面写入你的方法:

export function getUrl(bundleUrl,fileName,dir,host){
    var nativeBase;
    var isAndroidAssets = bundleUrl.indexOf('file://assets/') >= 0;
    var isiOSAssets = bundleUrl.indexOf('file:///') >= 0 && bundleUrl.indexOf('WeexDemo.app') > 0;
    if (isAndroidAssets) {
        nativeBase = 'file://assets/';
    }
    else if (isiOSAssets) {
        nativeBase = bundleUrl.substring(0, bundleUrl.lastIndexOf('/') + 1);
    }
    else {
        host = host||'localhost:8081';
        var matches = /\/\/([^\/]+?)\//.exec(bundleUrl);
        if (matches && matches.length >= 2) {
            host = matches[1];
        }
        nativeBase = 'http://' + host + '/' + dir + '/';
    }
    var h5Base = './index.html?page=./' + dir + '/';
    // in Native
    var base = nativeBase;
    if (typeof window === 'object') {
        base = h5Base;
    }
    return base+fileName;
}

如果你需要多个方法怎么办?没关系,继续往里面添加,按照上面的格式:

export function 方法名1(参数){

}
export function 方法名2(参数){

}
export function 方法名3(参数){

}

是不是很简单呢?
3.使用,方法写好了,怎么来用呢:
在你用的地方,js里面,像引入文件一样直接引入方法名:

<script>
  import {getUrl} from "./function";  //这里的路径不同的位置可能存在差异,你懂的哦
</script>

然后在使用的时候,比如我要做一个本地的跳转:

bigAction(index){
        console.log('will jump')
        navigator.push({
          url: getUrl(weex.config.bundleUrl,'homeBig.js'),
          animated: "true"
        }, event => {
          modal.toast({ message: 'callback: ' + event })
        })
      },

直接用名字即可,缺点是每次用的时候都要引入,要想类似iOS中pch的效果博主还没有找到,如果知道了会再更新,欢迎知道的小伙伴留言。

猜你喜欢

转载自blog.csdn.net/codingfire/article/details/79791737