前端開發-Weex初試


1 Weex介紹

weex是阿里2016年開源的一套跨移動端(Andriod/IOS/Wap)的前端框架,采用VUE,較React Native入門相對簡單 

官網地址

2 Weex安裝與初始化

2.1 安裝NodeJS和NPM

略過,默認安裝了

注意:nodejs的版本須大於4.5.0

2.2 安裝weex

  • npm install -g week-toolkit,全局安裝week工具集合
  • 安裝完成后命令行輸入weex,查看是否有命令幫助內容,如果提示沒有weex命令,表示weex沒有安裝好,檢查一下nodejs的版本

2.3 初始化一個項目

  • 新建一個項目目錄
  • 命令行輸入 weex init,這時會自動下載和生成相關文件
  • 運行npm install,安裝相關依賴包

2.4 與IDE集成

我使用的是WebStrom
  • 將剛才新建的工程導入webstrom中
  • 在setting->plugins中安裝weex的插件:weex、weex langugge support,用於創建we文件和支持weex語法(VUE)
  • 直接在webstrom的終端中運行weex相關命令

2.5 相關命令

  • weex ***.we : 運行調試xxx頁面,支持熱加載,默認端口是8081和8082 8082是熱加載端口
  • npm run build : build 在package.json定義的腳本命令,執行webpack
  • npm run dev : dev 在package.json定義的腳本命令,執行webpack --watch
  • npm run serve : serve package.json定義的腳本命令,啟動serve服務
  • weex xxx.we --qr: 運行調試xxx頁面,並依據地址url生成二維碼,主要是在iOS和Android上查看效果,設備須在同一個局域網中

webpack和serve的依賴包需要安裝

3 第一個Weex項目

3.1 主頁面

3.1.1 main.we

<template>
	<scroller>
  		<text>用戶名:</text>
  		<input id="top" type="text" autofocus="true" placeholder="請輸入用戶名" value="{{username}}"  oninput="usernameoninput" style="margin-top: 200px;margin-left: 200px;font-size:32px;">
  		</input>
  		<text>密碼:</text>
  		<input type="password" autofocus="true" placeholder="請輸入密碼" value="{{password}}" oninput="passwordoninput" style="margin-top: 200px;margin-left: 200px;font-size:32px;">
  		</input>
  		<input type="success"  value="登錄" onclick="login" style="margin-top: 200px;margin-left: 200px;">
		</input>
	</scroller>
</template>

<style>

</style>

<script>
var common = require('./lib/common.js');
module.exports = {
	data: {
  	root:"dist",
  	username:"",
  	password:""
	},
	ready: function () {
	},
	methods:{
  	login:function(e){
    	var storage = require('@weex-module/storage');
    	var self = this;
    	var bundleUrl = this.$getConfig().bundleUrl;
    	var url = common.getUrl(bundleUrl,'mainindex.lib','dist');
    	storage.setItem('username', self.username, function(e) {
      	self.$openURL(url)
    	});
  	},
  	usernameoninput:function(e){
    	this.username = e.value;
  	},
  	passwordoninput:function(e){
    	this.password = e.value;
  	}
	}
}
</script>

3.1.2 內置組件使用

3.1.2.1 數據存儲與讀取

var storage = require('@weex-module/storage');//引入存儲
storage.setItem('username', self.username, function(e) {//將用戶名存進客戶端,對應的key是usernam  
    
});

var storage = require('@weex-module/storage');
var self = this;
storage.getItem("username",function(e){//讀取數據
 	self.headinfo = e.data;
});

3.1.2.2 數據請求

var stream = require('@weex-module/stream');
stream.fetch({
   	method: 'GET',
   	url: "http://192.168.169.124:3000/testhttpget.do",
   	type:'json'
}, function(response) {
   self.body =  response.data.info;
},function(response){
	
});

其他內置組件使用,請參看API

3.2 自定義組件

3.2.1 新建we文件

<template>
	<div class="headclass">
    	<text>{{headinfo}}</text>
	</div>
</template>

<script>
	module.exports = {
    	data:{
        	headinfo:"welcome to this"
    	},
    	ready:function(){
        	var storage = require('@weex-module/storage');
        	var self = this;
        	storage.getItem("username",function(e){
            	self.headinfo = e.data;
        });
    }
}
</script>

<style>
.headclass{
    margin-top: 200px;
}
</style>

3.2.2 引入

<script>
require('./components/headdiv.we')
module.exports = {
    data:{

    }
}
</script>

3.2.3 使用

<template>
	<div class="bg">
    	<headdiv></headdiv>
	</div>
</template>

3.3 引用JS文件與打包

3.3.1 定義JS

	var getUrl = function(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:8080';
    		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;
	}

3.3.2 引用

var common = require('./lib/common.js');

打包

require('webpack')
require('weex-loader')

var path = require('path')

module.exports = {
	entry: {//主we頁面
	main: path.join(__dirname, 'src', 'main.we?entry=true')
},
output: {
 	path: 'dist',
	filename: '[name].lib'
},
module: {
loaders: [
  {
    test: /\.we(\?[^?]+)?$/,
    loaders: ['weex-loader']
  },
  {
    test: /\.js$/,
    loaders: ['weex-loader']  //將js文件打包
  }
  ]
}}

3.4 頁面跳轉

self.$openURL(url)

須要注意Android和iOS的跳轉,要提前定義好相關協議

4 與Android的集成

4.1 創建工程

創建Android 工程

4.2 引入weex

  • 下載源碼 git clone https://github.com/alibaba/weex
  • File->New-Import Module->選擇WEEX SDK Module(weex/android/sdk)->Finish
  • app 的build.gradle 中添加如下依賴:compile project(':weex_sdk')

4.3 引入相關組件

apply plugin: 'com.android.application'

android {
	compileSdkVersion 24
	buildToolsVersion "25.0.0"
	defaultConfig {
    	applicationId "demo.android.weex.tomsnail.cn.weexandroiddemo"
    	minSdkVersion 21
    	targetSdkVersion 24
    	versionCode 1
    	versionName "1.0"
    	testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
	}
	buildTypes {
    	release {
        	minifyEnabled false
        	proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    	}
	}
}

dependencies {
	compile fileTree(dir: 'libs', include: ['*.jar'])
	androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
    	exclude group: 'com.android.support', module: 'support-annotations'
	})
	compile 'com.android.support:appcompat-v7:24.2.1'
	compile 'com.android.support:design:24.2.1'
	compile 'com.taobao.android:dexposed:0.1.8'
	compile 'com.loopj.android:android-async-http:1.4.9@aar'
	compile 'com.facebook.fresco:fresco:0.12.0+'
	compile 'com.facebook.fresco:animated-gif:0.12.0'

	compile 'com.squareup.okhttp:okhttp:2.3.0'
	compile 'com.squareup.okhttp:okhttp-ws:2.3.0'
	compile 'com.squareup.okio:okio:1.0.1'
	compile 'com.alibaba:fastjson:1.1.46.android'
	compile 'com.android.support:support-annotations:23.2.1'
	compile 'com.jakewharton.scalpel:scalpel:1.1.2'
	compile 'com.squareup.picasso:picasso:2.5.2'
	//compile 'com.google.android.gms:play-services-appindexing:8.1.0'
	compile 'com.taobao.android:weex_inspector:0.0.8.1'
	compile project(':weex_sdk')
	testCompile 'junit:junit:4.12'
	compile 'com.google.android.gms:play-services-appindexing:8.4.0'
}

4.4 創建基礎類

  • WXApplication
  • ImageAdapter
  • MainActivity

4.5 配置AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="demo.android.weex.tomsnail.cn.weexandroiddemo">

<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission
    android:name="android.permission.WRITE_EXTERNAL_STORAGE">
</uses-permission>
<application
    android:name=".WXApplication"
    android:allowBackup="false"
    android:icon="@mipmap/ic_launcher"
    android:label="weexandroiddemo"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".Main1Activity">

    </activity>
    <!-- ATTENTION: This was auto-generated to add Google Play services to your project for
 App Indexing.  See https://g.co/AppIndexing/AndroidStudio for more information. -->
    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />
</application>

</manifest>

4.6 加入js

在src下新建assets文件夾,將weex生成的dist下的文件放入以便加載  WXFileUtils.loadAsset(path, context)

4.7 運行

連接設備運行app,建議使用真機,使用模擬機占用電腦資源較多

5 相關問題

5.1 升級

  • 依據版本號規划進行升級
  • 打包下載,本地解壓存儲、文件緩沖

5.2 自定義事件

  • 定義好相關協議
  • SPA化

5.3 消息與推送

  • 只做Native功能

5.4 Native功能

  • 比如拍照上傳、相冊等功能還是需要移動端開發人員開發和集成

5.5 持續集成

  • 重新定義集成流程,將weex的發布與移動端的發布聯合定義

相關代碼在整理后近期放在github上


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM