最近阿里的weex又發(fā)布了卿拴,于是去看了下weex文檔赤惊,然后開始擼碼吼旧,但是本人不會js,踩了居多的坑未舟。下面來擼下weex和nativie之間的數(shù)據(jù)交換黍少。
據(jù)小白我的了解寡夹,weex和native交互有二種方式。1厂置、用本地module的方式菩掏,讓weex調(diào)用本地的代碼。2昵济、還是用本地的module的方法智绸,利用JScallback的方式,將native的數(shù)據(jù)傳給weex访忿。下面就通過簡單的擼一把demo
方式一:js調(diào)Native
通過weex的調(diào)用本地的module中的方法瞧栗,并且利用本地的Toast顯示數(shù)據(jù)『C可以在文本框中輸入數(shù)據(jù)迹恐,在native中得到數(shù)據(jù)。
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卧斟、本地需要新建一個(gè)類殴边,名字叫LogModule繼承WXModule
2、在LogModule的方法必須是public珍语,方法頭部加上 @@JSMethod注解锤岸。
3、在Application中注冊module板乙,或者在初始化的時(shí)候注冊是偷。
WXSDKEngine.registerModule("testmodule", TestModule.class);
注意:這里的注冊名字,也就是"testmodule"和test1.we的 require('@weex-module/testmodule').printLog("hello weex");
中的testmodule需要一直募逞,否則雖然js不會報(bào)錯(cuò)蛋铆,但是卻得不到效果。
public class TestModule extends WXModule {
@JSMethod
public void printLog(String str){
Toast.makeText(mWXSDKInstance.getContext(), str, Toast.LENGTH_SHORT).show();
}
}
最后得到結(jié)果放接,在Android手機(jī)上回吐司得到hello weex.
方法二:JSCallBack
利用JSCallBack的方式戒职,將native的數(shù)據(jù)傳給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);
//調(diào)用nativie中的方法打日志洪燥,得出回調(diào)成功了
require('@weex-module/testmodule').log(map);
})
}
}
}
</script>
<style>
</style>
native中的代碼:
和之前一個(gè)一樣,我是吧三個(gè)方法寫在一個(gè)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);該方法可以調(diào)用多次
callback.invoke(map);該方法只會調(diào)用一次。
最終結(jié)果:
Paste_Image.png