zoukankan      html  css  js  c++  java
  • 前端开发-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上

  • 相关阅读:
    【leetcode】Binary Search Tree Iterator
    【leetcode】Palindrome Partitioning II
    【leetcode】Best Time to Buy and Sell Stock III
    【leetcode】Best Time to Buy and Sell Stock II
    【leetcode】Longest Consecutive Sequence
    【leetcode】Factorial Trailing Zeroes
    【leetcode】Simplify Path
    【leetcode】Generate Parentheses
    【leetcode】Combination Sum II
    【leetcode】Combination Sum
  • 原文地址:https://www.cnblogs.com/TomSnail/p/6072587.html
Copyright © 2011-2022 走看看