javascript - 使用weex.registerModule注册module,如何注册到全局?
本文介绍了javascript - 使用weex.registerModule注册module,如何注册到全局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
期望注册一个module,像访问 modal那样在需要的地方直接weex.requireModule('modal')使用。按照下边的代码运行,点击按钮的时候会提示找不到fetch属性。
Uncaught TypeError: Cannot read property 'fetch' of undefined
weex -v
v1.0.3
我的文件目录
|--app.js
|--src
|----test.vue
|----nativeApi.js
...
app.js是入口文件
import nativeApi from './src/nativeApi.js'
//注册自定义组件
weex.install(nativeApi);
import foo from './src/test.vue'
foo.el = '#root'
export default new Vue(foo);
nativeApi.js
const api = {
fetch:function(options,callback){
console.log('fetch called');
}
};
export default {
init : function(weex){
console.log('api init');
weex.registerModule('api',api);
}
};
test.vue
<template>
<text @click="testApi">testEvent</text>
</template>
<style></style>
<script>
var api = weex.requireModule('api');
export default {
methods:{
testApi : function(){
api.fetch();
}
}
}
</script>
补充:
页面加载后,通过控制台输入以下代码
weex.requireModule('api').fetch();
// 输出 'fetch called'
由此是否可以推断,weex.requireModule的时机有问题?
解决方案
我的解决方案:module定义完成就立即install,在需要的地方直接引用对应的js文件
import '../../source/module/util.js
const util = {
log :function(level, tag, msg){
var levelName = '';
switch(level){
case 'd':
levelName = 'debug';
break;
default : levelName = 'log';
}
console[levelName](tag,msg);
}
};
weex.install({
init : function(weex){
weex.registerModule('util',util);
}
});
这篇关于javascript - 使用weex.registerModule注册module,如何注册到全局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文