最近阿里的weex又發布了,于是去看了下weex文檔,然后開始擼碼,但是本人不會js,踩了居多的坑。下面來擼下weex和nativie之間的數據交換。
據小白我的了解,weex和native交互有二種方式。1、用本地module的方式,讓weex調用本地的代碼。2、還是用本地的module的方法,利用JScallback的方式,將native的數據傳給weex。下面就通過簡單的擼一把demo
方式一:js調Native
通過weex的調用本地的module中的方法,并且利用本地的Toast顯示數據??梢栽谖谋究蛑休斎霐祿?,在native中得到數據。
test1.we的代碼如下:
<template>
<div>
<text onclick="handler">hello world</text>
</div>
</template>
<script>
module.exports = {
data: {
},
methods: {
handler:function() {
require('@weex-module/testmodule').printLog("hello weex");
}
}
}
</script>
<style>
native代碼:
1、本地需要新建一個類,名字叫LogModule繼承WXModule
2、在LogModule的方法必須是public,方法頭部加上 @@JSMethod注解。
3、在Application中注冊module,或者在初始化的時候注冊。
WXSDKEngine.registerModule("testmodule", TestModule.class);
注意:這里的注冊名字,也就是"testmodule"和test1.we的 require('@weex-module/testmodule').printLog("hello weex");
中的testmodule需要一直,否則雖然js不會報錯,但是卻得不到效果。
public class TestModule extends WXModule {
@JSMethod
public void printLog(String str){
Toast.makeText(mWXSDKInstance.getContext(), str, Toast.LENGTH_SHORT).show();
}
}
最后得到結果,在Android手機上回吐司得到hello weex.
方法二:JSCallBack
利用JSCallBack的方式,將native的數據傳給Weex。然后在weex做處理。
test2.we:
<template>
<div>
<text style="font-size: 50px; color: chocolate" onclick="callme">baidu</text>
</div>
</template>
<script>
module.exports = {
data: {},
methods: {
callme:function() {
var mode=require('@weex-module/testmodule');
mode.printLogs("weex is beach",function (map){
//modal.toast({title:"wori",duration:2})
//console.log(map);
//調用nativie中的方法打日志,得出回調成功了
require('@weex-module/testmodule').log(map);
})
}
}
}
</script>
<style>
</style>
native中的代碼:
和之前一個一樣,我是吧三個方法寫在一個module中了。
public class TestModule extends WXModule {
@JSMethod
public void printLog(String str){
Toast.makeText(mWXSDKInstance.getContext(), str, Toast.LENGTH_SHORT).show();
}
/*****jscallback*****/
@JSMethod
public void printLogs(String str, JSCallback callback){
Toast.makeText(mWXSDKInstance.getContext(), str, Toast.LENGTH_SHORT).show();
Map<String, Object> map = new HashMap<>();
map.put("caicai", "my");
callback.invokeAndKeepAlive(map);
//callback.invoke(map);
}
@JSMethod
public void log(String str){
Log.e("123", str);
}
}
1、callback.invokeAndKeepAlive(map);該方法可以調用多次
callback.invoke(map);該方法只會調用一次。
最終結果:
Paste_Image.png