目录
1. 内置模块
1. webview
2. webSocket
3. stream 网络请求
4. storage 数据存储
5. picker 选择器
6. navigator 切换页面
7. modal 弹窗
8. meta 页面信息
9. globalEvent 监听事件
10. dom
11. clipboard 粘贴板
12. animation 动画
2. 自定义模块
1. 内置模块
- webview
用于webview 向前、向后、刷新
var webElement = this.$el('webview');
// 获取webview内置模块
var webview = weex.requireModule('webview');
// 上一页
webview.goBack(webElement.ref);
// 或者 webview.goBack(this.$refs.webview);
// 下一页
webview.goForward(webElement.ref);
// 刷新当前 Web 页面
webview.reload(webElement.ref);
// 向当前 Web 页面发送数据
webview.postMessage(webElement, {message: 'message to Web page'});
// Web 页面中接收数据
window.addEventListener('message', event => {
console.log(event.data) // message to Web page
})
- webSocket
使得在用户的 H5/iOS/Android 和一个服务器之间打开一个的交互式通信会话,可以向服务器发送消息, 并接收事件驱动的响应, 无需轮询服务器的响应。
安卓需要自定义 adapter ,iOS和h5默认实现。
<script>
// 1、获取websocket内置模块
var websocket = weex.requireModule('webSocket')
export default {
methods: {
// 自定义方法
connect:function() {
// 2、创建 WebSockets,并连接服务器
// 参数:URL,WebSockets 协议
websocket.WebSocket('ws://echo.websocket.org','');
var self = this;
self.onopeninfo = 'connecting...'
// 2.1、监听:连接打开、数据发送、连接出错、关闭
websocket.onopen = function(e)
{
self.onopeninfo = 'websocket open';
}
websocket.onmessage = function(e)
{
self.onmessage = e.data;
}
websocket.onerror = function(e)
{
self.onerrorinfo = e.data;
}
websocket.onclose = function(e)
{
self.onopeninfo = '';
// 服务器返回关闭的状态码
self.onerrorinfo = e.code;
// 服务器返回的关闭原因
e.reason
// 是否完全关闭
e.wasClean
}
},
// 自定义方法
send:function(e) {
var input = this.$refs.input;
input.blur();
// 3、向服务器发送数据
// 参数:data数据
websocket.send(this.txtInput);
this.sendinfo = this.txtInput;
},
// 自定义方法
close:function(e) {
// 4、关闭 WebSockets 的链接
// 参数( 关闭连接的状态号,关闭的原因)
websocket.close();
},
}
}
</script>
- stream 网络请求
请求网络
fetch(options, callback[,progressCallback])
默认 Content-Type 是 ‘application/x-www-form-urlencoded’,设置请求类型为json:将 Content-Type 设为 ‘application/json’。
参数说明:
1、options
method {string}:HTTP方法 (GET 或是 POST)
url {string}:URL
headers {Object}:HTTP 请求头
type {string}:响应类型, json、text、jsonp {在原生实现中其实与 json 相同)
body {string}:HTTP 请求体。不能传json、GET 请求不支持。
2、callback {Function}
status {number}:返回的状态码
ok {boolean}:如果状态码在 200~299 之间就为真。
statusText {string}:状态描述文本
data {Object | string}: 返回的数据。如果请求类型是 json 和 jsonp,则它就是一个 object ,如果不是则它就是一个 string。
headers {Object}:响应头
3、progressCallback {Function}
readyState {number}:当前状态
state:’1’: 请求连接中
opened:’2’: 返回响应头中
received:’3’: 正在加载返回数据
status {number}:响应状态码.
length {number}:已经接受到的数据长度. 你可以从响应头中获取总长度
statusText {string}:状态文本
headers {Object}:响应头
<script>
var stream = weex.requireModule('stream');
module.exports = {
data: function () {
return {
getJsonpResult: 'loading...',
}
},
created: function() {
var GET_URL = 'http://httpbin.org/get';
// 请求网络
stream.fetch({
method: 'GET',
url: GET_URL,
type:'json'
}, function(ret) {
if(!ret.ok){
this.getJsonpResult = "request failed";
}else{
console.log('get:'+ret);
//
this.getJsonpResult = JSON.stringify(ret.data);
}
},function(response){
console.log('get in progress:'+response.length);
});
}
};
</script>
- storage 数据存储
数据永久存储、修改、删除
1、H5只能存储小于5M的数据, Android 和 iOS没限制。
<script>
// 1、获取内置storage模块
const storage = weex.requireModule('storage')
// 2、设值/更新值
// key,value:不允许是 "" 或 null
storage.setItem('name', 'helloWorld', event => {
// 以下3、4、5同理
if(event.result=='success'){ // 设值成功
console.log('set success')
}
if(e.data==undefined){ // 设值成功
}else if(e.data==invalid_param){ // 失败,invalid_param 表示 key/value 为 "" 或者 null
}
})
// 3、获取值
storage.getItem('name', event => {
console.log('get value:', event.data)
})
// 4、删除值
storage.removeItem('name', event => {
console.log('delete value:', event.data)
})
// 5、遍历所有键
storage.getAllKeys(event => {
if (event.result === 'success') {
// event.data.join(', ')
}
})
// 6、获取总个数
storage.length(event => {
if (event.result === 'success') {
}
})
- picker 选择器
用于数据选择,日期选择,时间选择
H5模块如需使用,请手动引入weex-picker组件
pick(options, callback[options]) 弹出单选选择器
1、options {Object}:
index {number}:默认选中选
items {array}:数据源
textColor {color}:文本颜色
selectionColor {color}:选中item的背景色
confirmTitle {string}:确认按钮文本
cancelTitle {string}:取消按钮文本
confirmTitleColor {color}:确认按钮的文字颜色
cancelTitleColor {color}:取消按钮的文字颜色
title {string}:对话框的标题
titleColor {color}:对话框标题的文字颜色
titleBackgroundColor {color}:对话框标题的背景色
2、callback {function (ret)}:
执行完读取操作后的回调函数。
ret两属性:
result {string}: success、cancel、error
data {number}:选择的选项,仅成功确认时候存在。
pickDate(options, callback[options]) 弹出日期选择器
1、options {Object}:
value {string}:必选,date picker 选中的值,date 的字符串格式为yyyy-MM-dd
max {string}:可选,date 的最大值
min {string}:可选,date 的最小值
2、callback {function (ret)}:执行完读取操作后的回调函数。
ret两属性:
result {string}:success、cancel、error
data {string}:选取的值,格式为 yyyy-MM-dd, 仅成功确认时存在。
pickTime(options, callback[options]) 弹出时间选择器
1、options {Object}:
value {string}:必选,time 格式为 HH:mm
2、callback {function (ret)}:执行完读取操作后的回调函数。
ret两属性:
result {string}:success、cancel、error
data {string}:time 格式为 HH:mm, 仅成功确认的时候存在。
<script>
// 获取内置picker模块
const picker = weex.requireModule('picker')
export default {
data () {
return {
value: ''
}
},
methods: {
pickTime () {
// 弹出时间选择器
picker.pickTime({
value: this.value
}, event => {
if (event.result === 'success') {
this.value = event.data
}
})
}
}
}
</script>
- navigator 切换页面
切换页面
push(options, callback)
1、options {Object}:
url {string}:要压入的 Weex 页面的 URL
animated {string}:默认值为 "true" 有动画效果,"false" 则无。注意是字符串不能是布尔类型。
2、callback {Function}:执行完该操作后的回调函数
pop(options, callback)
1、options {Object}:
animated {string}:默认值为 "true" 有动画效果,"false" 则无,
2、callback {Function}:执行完该操作后的回调函数
// 获取navigator内置模块
var navigator = weex.requireModule('navigator')
// push下一页
navigator.push({
url: 'http://dotwe.org/raw/dist/519962541fcf6acd911986357ad9c2ed.js',
animated: "true"
}, event => {
})
// pop回上一页
navigator.pop({
animated: "true"
}, event => {
})
- modal 弹窗
toast(options) 弹出后过段时间消失
options {Object}:
message {string}:内容
duration {number}:持续时间(以秒为单位)
Android: 大于3s则使用LONG, 否则使用SHORT。
iOS: 同Duration相同
alert(options, callback) 警告框
options {Object}:
message {string}:内容
okTitle {string}:确定按钮文本,默认是“OK”
callback {Function}:用户操作完成后的回调
confirm(options, callback) 确认框
options {object}:
message {string}:内容
okTitle {string}:确定按钮文本,默认是“OK”
cancelTitle {string}:取消按钮文本,默认是 Cancel
callback {function (result)}:
用户操作完成后的回调
result是按钮文本
prompt(options, callback) 提示框(可获取输入)
options {object}:
message {string}:内容
okTitle {string}:确定按钮文本,默认是“OK”
cancelTitle {string}:取消按钮文本,默认是 Cancel
callback {function (ret)}:
用户操作完成后的回调
result {string}:用户按下的按钮文本
data {string}:用户输入的文本
// 获取modal内置模块
var modal = weex.requireModule('modal')
// toast
modal.toast({
message: 'This is a toast',
duration: 0.3
})
// alert
modal.alert({
message: 'This is a alert',
duration: 0.3
}, function (value) {
console.log('alert callback', value)
})
// confirm
modal.confirm({
message: 'Do you confirm ?',
duration: 0.3
}, function (value) {
console.log('confirm callback', value)
})
// prompt
modal.prompt({
message: 'This is a prompt',
duration: 0.3
}, function (value) {
console.log('prompt callback', value)
})
- meta 页面信息
默认情况下,应用无需修改此配置
setViewport(options)
改变页面的显示宽度,仅对当前页面生效
只有在页面渲染开始之前设置 viewport 才会生效,在new Vue(App)之前。
options:
width: 数值、device-width、device-height。
height: 数值、device-width、device-height。
宽度和高度的单位默认是 px,暂不支持其他单位。
// entry.js
import App from './app.vue'
const meta = weex.requireModule('meta')
// 配置 viewport 的宽度为 640px
meta.setViewport({
width: 640
})
App.el = '#root'
new Vue(App)
// app.vue
<template>
...
</template>
<style scoped>
...
</style>
- globalEvent 监听事件
目前只有 platform 为 iOS 和 Android 才能支持
addEventListener(String eventName, String callback) 添加全局监听
removeEventListener(String eventName) 取消监听
发送事件
iOS
VC中
[weexInstance fireGlobalEvent:@"geolocation" params:@{@"key":@"value"}];
Android
Map<String,Object> params=new HashMap<>();
params.put("key","value");
mWXSDKInstance.fireGlobalEventCallback("geolocation",params);
// 获取globalEvent内置模块
var globalEvent = weex.requireModule('globalEvent');
// 添加全局监听
globalEvent.addEventListener("geolocation", function (e) {
console.log("get geolocation")
});
// 取消监听
globalEvent.removeEventListener("geolocation");
WXApplicationDidBecomeActiveEvent 应用进入前台时触发
WXApplicationWillResignActiveEvent 应用即将进入后台时触发
globalEvent.addEventListener("WXApplicationDidBecomeActiveEvent", function (e) {
console.log("WXApplicationDidBecomeActiveEvent");
});
- dom
1、获取某个组件的 bounding rect 布局信息
getComponentRect(ref, callback) v0.9.4+
2、滚动指定位置
scrollToElement(ref, options)
ref {Node}:你要滚动到的那个节点
options {Object}:
offset {number}: 到其可见位置的偏移距离,默认是 0
animated {boolean} 0.10+:是否动画,默认是true
3、添加一个 font-face rule
addRule(type, contentObject) v0.12.0+
type:fontFace 固定。
contentObject:
fontFamily: font-family的名称。
src: 字体地址
http://、https://、local://仅支持Android、file://、data://从base64读取
<script>
// 获取dom内置模块
const dom = weex.requireModule('dom')
// 滚动指定项位置(项的ref为item10)
const el = this.$refs.item10[0]
dom.scrollToElement(el, {})
dom.scrollToElement(el, { offset: 0 })
// 获取某个组件的 bounding rect 布局信息
const result = dom.getComponentRect(this.$refs.box, option => {
console.log('getComponentRect:', option)
// option.size
// size.width、size.height、size.top、size.bottom、size.left、size.right
})
// 自定义字体, 放在beforeCreate方法中
dom.addRule('fontFace', {
'fontFamily': "iconfont2",
'src': "url('http://at.alicdn.com/t/font_1469606063_76593.ttf')"
});
</script>
- clipboard 粘贴板
1、仅支持文本拷贝
2、出于安全考虑和平台限制,只支持 Android 和 iOS,不支持 html5。
getString(callback) 从系统粘贴板读取内容
callback {function (ret)}:执行完读取操作后的回调函数。
ret两属性:
ret.data:获取到的文本内容
ret.result:返回状态,success 、 fail。
setString(text) 复制到剪切板
text {string}:要复制到剪切板的字符串
<script>
// 获取clipboard内置模块
const clipboard = weex.requireModule('clipboard')
// 复制到剪切板
clipboard.setString('hello')
// 获取到的文本内容
clipboard.getString(ret => {
this.message = 'text from clipboard:' + ret.data
})
- animation 动画
对 位置、大小、旋转角度、背景颜色和不透明度等 进行动画
animation.transition(el, options, callback)
el:将要执行动画的元素
options:
styles(object):
width
height
backgroundColor
opacity
transformOrigin 参数 x-aris、 可能的值为 left、center、right、长度值或百分比值, 参数 y-axis 可能的值为 top、center、bottom、长度值或百分比值
transform
translate/translateX/translateY 像素值或百分比
rotate 单位是度
scale/scaleX/scaleY
rotate/rotateX v0.14+ /rotateY v0.14+
perspective v0.16+ 观察者距离z=0平面的距离,在Android 4.1及以上有效
duration(number):动画持续时间 (单位是毫秒),默认值是 0
delay (number):动画延迟时间(单位是毫秒),默认值是 0
needLayout (boolean):节点动画执行时是否产生布局动画即LayoutAnimation,默认值是false。
timingFunction (string):动画执行的速度曲线,用于使动画变化更为平滑。默认值是 linear,表示动画从开始到结束都拥有同样的速度。
linear 匀速
ease 变慢
ease-in 慢快
ease-out 快慢
ease-in-out 先加速到达中间点后减速到达终点
cubic-bezier(x1, y1, x2, y2) 三次贝塞尔函数,参数值必须处于 0 到 1 之间。
callback:动画执行完后的回调函数。仅支持在iOS平台上获取动画执行是否成功的信息。
<script>
// 获取animation内置模块
const animation = weex.requireModule('animation')
animation.transition(ref1, {
styles: {
backgroundColor: '#FF0000',
transform: 'translate(250px, 100px) scale(1.5)',
transformOrigin: 'center center'
},
duration: 800, //ms
timingFunction: 'ease',
needLayout:false,
delay: 0 //ms
}, function () {
})
2. 自定义模块
第一步:创建自定义模块
: NSObject<WXModuleProtocol>
.m文件中+
@synthesize weexInstance;
// 暴露接口
WX_EXPORT_METHOD(@selector(call:withParam:callback:))
// 接口实现
- (void)call:(NSString *)api withParam:(NSDictionary *)param callback:(WXModuleKeepAliveCallback)callback{
NSLog(@"hello");
}
第二步:注册自定义模块
AppDelegate的didFinishLaunchingWithOptions方法中+
[WXSDKEngine registerModule:@"wxmodule" withClass:[WXModule class]];
第三步:vue文件中使用
var wxmodal = weex.requireModule('wxmodule')
wxmodal.call('api',{},function(){
});
网友评论