体验 weex —— 写一个表情包应用

culj5457 8年前
   <p>前些时间体验 ReactNative 的时候写了一个 2333 表情包 app,这次使用 weex 写一下。 weex 通过自己的一套 sdk 可以将一个 js 文件渲染成一个 native (android 或 iOS )的 view 对象。 weex 语法参照 vue ,看过一点 vue 的文档所以写起来可以很快上手。有一点感受 weex 的文档感觉没有 RN 的清晰,还有尺寸单位还没搞清楚,浏览器预览的和生成的 android 版还是有差距,和 iOS 也尺寸不太对。</p>    <p><img src="https://simg.open-open.com/show/dd9d44d896d894b42ac7ff2b54884b9b.jpg"></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/ee868dc6b7bad346f49808b1cbfa0864.gif"></p>    <p style="text-align:center"><img src="https://simg.open-open.com/show/28876e31e42f70064f28fbd778f524e8.gif"></p>    <h2><strong>安装 weex</strong></h2>    <pre>  <code class="language-javascript">npm install -g weex-toolkit  </code></pre>    <h2><strong>创建 index.we 文件</strong></h2>    <p>和 vue 类似 template 中放布局, style 放css, script 操作数据。</p>    <pre>  <code class="language-javascript"><template>   <div class="main">   <list class="main-list">   <cell class="{{ isSelected ? 'row-select' :'row' }}" repeat="{{rows}}" index="{{$index}}" onclick="changeTid" tid={{tid}}>   <div class="item">   <text class="item-title">{{ title }}</text>   </div>   </cell>   </list>   <list class="main-detail">   <cell class="image-row" repeat="{{ imageList }}" >   <div class="image-item">   <div repeat="{{data}}">   <image style="width:198;height:198;" src="{{ link }}"></image>   </div>   </div>   </cell>   </list>   </div>  </template>    <style>  .main{   flex-direction: row;   background-color: #eceff1;   color: #333333;  }  .main-list{   flex: 1;   align-items: stretch;  }  .main-detail{   flex: 4;  }  .row {   background-color: white;  }  .row-select {   background-color: #e1e1e1;  }  .item {   justify-content: center;   border-bottom-width: 2;   border-right-width: 2;   border-bottom-color: #eceff1;   border-right-color: #eceff1;   height: 68;   padding-left: 10;   padding-right: 10;  }  .image-item{   justify-content: space-between;   flex-direction: row;   height: 202;  }  .item-title {   font-size: 24;   text-overflow: ellipsis;  }    </style>    <script>    // 使用的组件  require('weex-components');  module.exports = {   data: {   rows: [],   imageList: [],   currentTid: 128   },     created: function () {   this.getCategory()   this.getImage(this.currentTid)   },     methods: {   getCategory: function(tid) {   var that = this   var stream = require('@weex-module/stream');   // 直接使用 fetch 以及 => 在预览中没问题,生成的 js 文件在 Android 版本渲染不出来,好像是不能直接支持 ES6 语法   stream.fetch({   method: 'GET',   url: 'https://api.leancloud.cn/1.1/classes/Category',   headers: {   'X-LC-Id': 'ffTooBOPa3NxxjEo91dVYEel-gzGzoHsz',   'X-LC-Key': 'aysIBDNEvw1n063qpf7Jx9jb',   'Content-Type': 'application/json'   },   }, function(ret) {   if(!ret.ok){   console.log( "request failed")   }else{   var json = JSON.parse(ret.data)   var list = json.results   for(var i=0;i < list.length; i++){   var item = list[i]   item.isSelected = false   that.rows.push(item)   }   }   },function(response){   console.log(response);   });   },     getImage: function(tid) {   var that = this   var stream = require('@weex-module/stream');   stream.fetch({   method: 'GET',   url: 'https://api.leancloud.cn/1.1/classes/Image?where={"tid":'+tid+'}}ℴ=-update_time',   headers: {   'X-LC-Id': 'ffTooBOPa3NxxjEo91dVYEel-gzGzoHsz',   'X-LC-Key': 'aysIBDNEvw1n063qpf7Jx9jb',   'Content-Type': 'application/json'   },   }, function(ret) {   if(!ret.ok){   console.log( "request failed")   }else{   var json = JSON.parse(ret.data)   var list = json.results   that.imageList.length = 0   for(var i = 0; i < list.length; i++){   var imageRow;   if (i % 3 == 0) {   imageRow = [];   that.imageList.push({'data':imageRow});   }   imageRow[i%3] = list[i];   }   console.log(that.imageList);   }   },function(response){   console.log(response);   });   },     changeTid: function (e) {   console.log(e);   this.currentTid = e.target.attr.tid   this.getImage(this.currentTid)   for (var i = 0; i < this.rows.length; i++) {   var row = this.rows[i]   row.isSelected = row.tid == this.currentTid   }   }   }  }  </script>  </code></pre>    <h2><strong>运行起来</strong></h2>    <p>浏览器中预览</p>    <pre>  <code class="language-javascript">weex index.we  </code></pre>    <p>生成 js 文件</p>    <pre>  <code class="language-javascript">weex index -o build.js  </code></pre>    <h2><strong>跑在 Android 项目中</strong></h2>    <p>新建 Android 项目, 在项目中添加 weex sdk 的依赖库。</p>    <p>app/build.gradle</p>    <pre>  <code class="language-javascript">dependencies {      compile fileTree(dir: 'libs', include: ['*.jar'])      testCompile 'junit:junit:4.12'      compile 'com.android.support:appcompat-v7:24.0.0'      compile 'com.android.support:recyclerview-v7:24.0.0'      compile 'com.github.bumptech.glide:glide:3.7.0'       compile 'com.alibaba:fastjson:1.1.46.android'      compile 'com.taobao.android:weex_sdk:0.7.0' // weex sdk      compile 'com.taobao.android:weex_inspector:0.0.2.7' // weex 调试 sdk ,这个必须得加  }  </code></pre>    <p>创建自己的 Application 类,然后 onCreated 中初始化 weex</p>    <pre>  <code class="language-javascript">/**   * Created by hanks on 16/9/5.   */  public class MyApp extends Application {      @Override      public void onCreate() {          super.onCreate();          WXEnvironment.addCustomOptions("appName", "TBSample");          InitConfig config = new InitConfig.Builder()                  .setImgAdapter(new ImageAdapter())                  .build();          WXSDKEngine.initialize(this, config);      }  }  </code></pre>    <p>初始化完成之后就是加载 js 了,将上一步生成的 js 复制到 assets 目录</p>    <pre>  <code class="language-javascript">public class MainActivity extends AppCompatActivity {        private FrameLayout mContainer;      private WXSDKInstance mWeexInstance;        @Override      protected void onCreate(Bundle savedInstanceState) {          super.onCreate(savedInstanceState);          setContentView(R.layout.activity_main);            mContainer = (FrameLayout) findViewById(R.id.container);          // sdk 实例          mWeexInstance = new WXSDKInstance(this);          mWeexInstance.registerRenderListener(new IWXRenderListener() {                // sdk 将 js 文件渲染成 view 对象回调              @Override              public void onViewCreated(WXSDKInstance wxsdkInstance, View view) {                  if (mContainer != null) {                      mContainer.addView(view); // 添加到界面                  }              }                @Override              public void onRenderSuccess(WXSDKInstance wxsdkInstance, int i, int i1) {                }                @Override              public void onRefreshSuccess(WXSDKInstance wxsdkInstance, int i, int i1) {                }                @Override              public void onException(WXSDKInstance wxsdkInstance, String s, String s1) {                }          });          // 加载 js 文件          mWeexInstance.render("Weex2333",                  WXFileUtils.loadAsset("build.js", this),                  null, null, -1, -1,                  WXRenderStrategy.APPEND_ASYNC);      }  }  </code></pre>    <p>然后运行 Android 项目。</p>    <p> </p>    <p> </p>    <p>来自:http://hanks.xyz/2016/09/05/weex-2333/</p>    <p> </p>