# Weex 实例变量
每个 Weex 页面的 JS 上下文中都有一个相互独立的 weex 变量,它可以像全局变量一样使用,不过它在不同页面中是隔离而且只读的。
注意: weex 实例变量只在 Vue 框架中暴露了,目前还不支持在 Rax 框架中使用。
# 属性和方法
Weex 实例变量的类型定义如下:
declare type Weex = {
  config: WeexConfigAPI;
  document: WeexDocument;
  requireModule: (name: string) => Object | void;
  supports: (condition: string) => boolean | void;
}
1
2
3
4
5
6
2
3
4
5
6
# Weex 环境变量
有时候为了兼容性或者为了增强某个端上的能力,需要编写平台特异的代码。 Weex 提供了 weex.config.env 和全局的 WXEnvironment 变量(它们是等价的)来获取当前执行环境的信息。
weex.config.env === WXEnvironment
1
# Weex 环境变量中的字段:
| 字段名 | 类型 | 描述 | 
|---|---|---|
| platform | String | Current running platform, could be "Android", "iOS" or "Web". | 
| weexVersion | String | The version of Weex SDK. | 
| appName | String | Mobile app name or browser name. | 
| appVersion | String | The version of current app. | 
| osName | String | The OS name, could be "Android" or "iOS". | 
| osVersion | String | The version of current OS. | 
| deviceModel | String | Mobile phone device model. (native only) | 
| deviceWidth | Number | Screen resolution width. | 
| deviceHeight | Number | Screen resolution height. | 
这个例子 (opens new window) 打印出了 Weex 环境对象中的所有值。
# 使用原生模块
你可以像使用不同 javascript 函数一样使用原生注册的接口。这里是一个简单的使用 modal 模块的例子: (opens new window)
<template>
  <div><text>Toast</text></div>
</template>
<script>
  const modal = weex.requireModule('modal')
  modal.toast({
    message: 'I am a toast.',
    duration: 3
  })
</script>
1
2
3
4
5
6
7
8
9
10
2
3
4
5
6
7
8
9
10
# 使用范例
检测某个组件是否可用:
weex.supports('@component/slider') // true
weex.supports('@component/my-tab') // false
1
2
2
检测某个模块是否可用:
weex.supports('@module/stream')  // true
weex.supports('@module/abcdef')  // false
1
2
2
检测某个模块是否包含某个方法:
weex.supports('@module/dom.getComponentRect') // true
weex.supports('@module/navigator.jumpToPage') // false
1
2
2
无效的输入:
weex.supports('div') // null
weex.supports('module/*') // null
weex.supports('@stream/fetch') // null
weex.supports('getComponentRect') // null
1
2
3
4
2
3
4
# isRegisteredModule
 检测某个特定的模块或者接口是否可用。
weex.isRegisteredModule(moduleName: string, methodName: string): boolean
1
这个接口只能用于检测特定模块和方法的兼容性,不支持检测组件。
weex.isRegisteredModule('stream') // true
weex.isRegisteredModule('stream', 'fetch') // true
weex.isRegisteredModule('whatever', '- unknown -') // false
weex.isRegisteredModule('div') // false, not support components
1
2
3
4
2
3
4
# isRegisteredComponent
 检测某个特定的组件是否可用。
weex.isRegisteredComponent(componentName: string): boolean
1
这个接口只能用于检测组件的兼容性,不支持检测模块。
weex.isRegisteredComponent('div') // true
weex.isRegisteredComponent('- unknown -') // false
weex.isRegisteredComponent('navigator') // false, not support modules
1
2
3
2
3
