nvue2
v1.0.45
Published
nvue vue2
Readme
npm version patch npm publish
此插件专用于uni-app的nVue
安装:npm install nuve2
在任意目录创建文件:config.js,结构见当前目录下
/example/config.js;在项目根目录
App.vue: 其中config.js指向实际位置
<script>
import install from 'nvue2/install';
import config from '@/common/config';
//扩展方法,可以引入多个,在页面中直接用:this.runtime....
import runtime from '@/common/runtime';
//可以引入多个
import mixin from '@/common/mixin';
export default {
computed: {
...install(config, { runtime }, [mixin])
},
}
</script>
- 控件引用:
- 在每个实际的nvue文件顶部引入:
import 'nvue2';, - 非APP项目只需在首页(pages.json的第一个页面)引入一次,其他页面:
<script>
// #ifdef APP-PLUS || H5
import 'nvue2';
// #endif
………………
</script>- 对象调用:
- 各页面可以直接调用本插件的几个基础对象:
app,api,db,pages,例:this.$api.post(...), - 也就是在这几个名称前加
$号,这几个对象合称为kernel对象;
- WebSocket侦听: WebSocket在APP启动时就与服务器连接,而且只有一个连接,收发方法:
- 发送:
- 方法1:
this.$send(action,message),无回调发送 - 方法2:
this.$send(action,message).then(res=>{}),有回调发送 - 实际发送的数据结构如下,注意其中index,在服务端返回数据时要带上,否则
有回调发送不工作。
- 方法1:
{
action: action,
time: Date.now(),
index: index,
message: message,
}- 接收:
- 在需要受理全局广播的页面methods中添加
onSocketMessage(data) {}方法,此方法只能接收到所有无回调发送的结果; - 注册了侦听的页面在发生回退的时候将取消当前页面的侦听,但是若页面的回退不是点击原生回退或其他情况发生页面跳转,而且跳转后不再需要继续侦听,需要在触发方法内执行
this.unlisten();;否则会造成侦听列表过长。
- 服务器返回:
- 客户端发送的数据中
index作为标识,要原样带回,若不带回,则将按无回调发送处理,也就是会被全局侦听处理; - 客户端发送的
action作为服务器端处理标识,返回也要返回action,但这是向客户端发送的处理标识,自行定义自行处理即可。 - 例如发送
{action:'register',…………},服务端返回{action:"newuser",……},则在需要处理newuser的页面中自行处理:
onSocketMessage(data) {
switch(data.action){
…………后续处理
}
}- 所有全局侦听都收到这些数据,当然也可以同时处理。
- 若
config.socket中定义了result对象,则上面所有返回值都是new result(DATA,KERNEL)的对象,DATA是服务器返回的数据原样,没有json序列化,若没有带result对象,则返回的数据是经过json序列化的。 - 也可以不采用上述方案,而是用uniapp自带的全局侦听方案:定义
result对象,在result的constructor中uni.$emit(eventName,OBJECT)触发,在需要的地方uni.$on(eventName,callback)或uni.$once(eventName,callback)
引入组件
pages.json中:
"easycom": {
"autoscan": true,
"custom": {
"^vue2-(.*)": "nvue2/components/$1/$1.vue"
}
}引入css
App.vue中
@import "nvue2/css/public.scss";