Weex框架学习使用与总结

1,235 阅读4分钟

1.modal模块

//modal模块
var modal = weex.requireModule('modal')
1.modal.toast(options)   
例:
modal.toast({
    message: 'This is a toast',  //展示内容
    duration: 0.3   //展示时间
})

2.modal.alert()弹窗
例:
modal.alert({
    message:'你的密码输入有误,请重新输入',
    okTitle:'是的,谢谢'
},res=>{   //回调 注意:无参数
                
    }
如果你使用默认的okTitle你可以这样写
modal.alert({message:'你的密码输入有误'})


modal.confirm(options,callback) //有确定或取消得弹出
例:
modal.confirm({
    message:'你是美女吗',
    okTitle:"是的",
    cancelTitle:'差一点点'
},res=>{
    if(res=="是的"){  //回调函数的参数 result 是确定按钮上的文字信息字符串
 
    }else if (res=="差一点点"){
 
    }
})
如果你使用系统默认的okTitle和cancelTtitle你可以这样写
 3.modal.confirm({
    message:'你是美女吗'
},res=>{
    if(res=="Ok"){
 
    }else if (res=="Cancle"){
 
    }
})


//带有输入框得弹框
4.modal.prompt({
    message:'请输入你的昵称',
    okTitle:'确定',
    cancelTitle:'取消'
    },res=>{
        if(res.result=='确定'){
 
        }else if (res.result=='取消'){
 
        }
    })

2.image

<image ref="poster" @load="onImageLoad" placeholder="" src="http://ww2.sinaimg.cn/large/006tKfTcgy1fez04i56w5j31hc0kuwhz.jpg" class="image" resize='stretch'></image>
//placeholder:占位符路径
注意:必须设置宽高
仅支持网络图片 
resize属性:stretch(默认值) contain cover

//save方法 保存图片到相册
const $image = this.$refs.poster
$image.save(result => {
  if (result.success) {
    //成功回调
  } else {
    console.log(result.errorDesc)
    // 失败回调
  }
})
//load 图片加载事件 
 onImageLoad (event) {
      if (event.success) {
        // Do something to hanlde success
      }
    }

3.list列表

注意:不允许同方向的list和scroller组件相互嵌套
//子组件 cell  
       header (可以吸附到顶部)
       refresh 下拉刷新      @refresh  下拉松手触发     @pullingdown  下拉行为触发
       loading 上拉加载      @loading

事件:
   laodmore:列表内容超出屏幕 下拉到底部触发的事件  @loadmore  需要设置loadmoreoffset属性>0
   重置loadmore   this.$refs["list"].resetLoadmore(); 
  
示例:
<template>
<div class="page">
    <list class="list" ref="list" loadmoreoffset="20">
     <refresh @pullingdown="pullingdown" :display="showLoading" @refresh="onrefresh" class="refresh">
   <text>下拉刷新</text>
    </refresh>
        <cell class="cell" v-for='(item,index) in list' :key="index">
            <image :src="item.src" class="poster"></image>
            <text class="title">{{item.title}}</text>
        </cell>
         <loading @loading="onloading" :display="showLoading" class="loading">
            <loading-indicator class="indicator"></loading-indicator>
            <text>加载更多</text>
          </loading>
    </list>
</div>
</template>

<script>
export default{
    data(){
        return{
            list:[
            {src:'https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1493829745671&di=68c663b03f829420e4f37c35d95d42b6&imgtype=0&src=http%3A%2F%2Fimg2.downza.cn%2Fapple%2Fipad%2Fyyyl-332%2F2016-04-22%2F0a60729df8603efa34de212ec67564ab.png',title:"优酷视频"},
            {src:'https://ss3.bdstatic.com/70cFv8Sh_Q1YnxGkpoWK1HF6hhy/it/u=228407861,2241632908&fm=23&gp=0.jpg',title:'爱奇艺'},
            {src:'https://ss0.bdstatic.com/70cFvHSh_Q1YnxGkpoWK1HF6hhy/it/u=3665454193,1922651319&fm=23&gp=0.jpg',title:'腾讯视频'},
            {src:'https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=2924906978,3545987802&fm=23&gp=0.jpg',title:'土豆视频'},
            {src:'https://ss1.bdstatic.com/70cFuXSh_Q1YnxGkpoWK1HF6hhy/it/u=1502096116,2161980529&fm=23&gp=0.jpg',title:'芒果TV'},
            ]
        }
    }
}
</script>
<style>
.poster{
    width:750px;
    height: 300px;  
}
.title{
    position:absolute;
    bottom: 20px;
    left:0px;
    right:0px;
    height: 88px;
    color:white;
    line-height: 88px;
    text-align: center;
    font-size: 40px;
    background-color: rgba(0,0,0,0.5);
}
</style>

4.scroller列表

//可以使用任意子组件 除了cell (建议使用list列表,scroller可能会造成苹果机型无法下拉)
基本同list列表组件
横向滚动  使用 scroll-direction="horizontal" 和 flex-direction: row;
<scroller class="scroller"  scroll-direction="horizontal" show-scrollbar="false" style="flex-direction: row;overflow-x: scroll;overflow-y: hidden;" ></scroller>

属性:show-scrollbar  是否显示滚动条  布尔值

5.slider轮播图


属性:interval:轮播时长        number(毫秒)
     auto-play:自动轮播        true/false
子组件:
indicator 指示器(小圆点) :
item-color这是指示器没被选中的颜色
item-selected-color设置指示器被选中的颜色
item-size指示器的圆点大小

检测轮播到哪一张图  可以使用 @change事件   有一个event参数(默认)
<template>
<div>
    <slider class="slider" interval="3000" auto-play="true">
      <image :src="src" v-for='(src,index) in images' @click='click(index)' class="image"> </image>
         <indicator class="indicator"></indicator>
    </slider>
</div>
</template>
<script>
export default{
    data(){
        return{
            images:['https://gd2.alicdn.com/bao/uploaded/i2/T14H1LFwBcXXXXXXXX_!!0-item_pic.jpg',
                    "https://gd1.alicdn.com/bao/uploaded/i1/TB1PXJCJFXXXXciXFXXXXXXXXXX_!!0-item_pic.jpg",
                    "https://gd3.alicdn.com/bao/uploaded/i3/TB1x6hYLXXXXXazXVXXXXXXXXXX_!!0-item_pic.jpg" ]
            
        }
    }
}
</script>
<style>
.slider{
    width:750px;
    height: 300px;
    background-color: green;
}
.image{
    width:750px;
    height: 300px;
}
    //需要设置绝对定位
.indicator{
    position:absolute;
    left:20px;
    bottom:40px;
    width:100px;
    height: 44px;
    item-color:red;
    item-selected-color:green;
    item-size:20px;
}
</style>

6.通用事件

clcik点击事件
appear  出现事件   给组件绑定
disappear   消失事件  给组件绑定
longpress长按事件
viewappear       给根组件  页面显示触发
viewdisappear   给根组件 页面隐藏触发

默认都携带了
target: 触发点击事件的目标组件
timestamp: 触发点击事件时的时间戳

7.switch开关

//安卓真机下 不显示,建议使用图片切换
<switch class="switch" checked="true" disabled="false" @change="change"> </switch>
属性:
checked: 开关状态
disabled:禁用状态
样式无法修改

change 事件  //按钮状态改变触发

8.storage模块

const storage = weex.requireModule('storage')
//存储数据:
storage.setItem(key, value, callback)  //key value都需要是字符串
//示例:
storage.setItem('cache',"要缓存的值",res=>{
    if(res.result=='success'){
    // 数据缓存成功
    }
})
//读取数据:
getItem(key, callback)
storage.getItem('cache',local_list=>{
    if(local_list.result=='success'){
       console.log(local_list.data)//拿到缓存的值,如果没有则为"undefined"
    }
})
//清除缓存:
removeItem(key, callback)
storage.removeItem('cache',res=>{
    if(res.result=='success'){
        modal.toast({message:'清除完成',duration:1})
    }
})
//获取存储的键值对数量:
length(callback)
storage.length(res=>{
    if(res.result='success'){
        this.length = res.data
    }
})
//获取存储的所有键名数组
getAllKeys(callback)
storage.getAllKeys(res=>{
    if(res.result=='success'){
      res.data.forEach((item)=>{
          storage.removeItem(JSON.stringify(item))        //遍历清除所有的缓存
      })
    }
})

9.布局

//必须使用flex布局  且默认flex
display:flex 设置root       //  标签的子标签的布局方式为flex 弹性布局
flex-direction:column        //子标签排列的方式为垂直排列
align-items: center;         //子标签沿着y轴居中对齐
justify-content:flex-start   //子标签的对齐方式,从开始的位置以此布局

10.dom模块

//用法:
const dom = weex.requireModule('dom')
<cell ref='item0'></cell>//静态
<cell :ref="item+'index'">//动态
 const el = this.$refs.item0[0]
dom.scrollToElement(el, {}) // 默认动画true 偏移量为0
    
获取组件的信息
    getComponentRect(ref, callback)
    callback参数:
    {
  result: true,
  size: {
    bottom: 60,
    height: 15,
    left: 0,
    right: 353,
    top: 45,
    width: 353
  }
}
    const el = this.$refs.item0[0]
const result = dom.getComponentRect(this.ref, option => {
      console.log('getComponentRect:', option)
 })
    
 //示例:   
<template>
  <scroller scroll-direction="horizontal" style="height:500px;width:750px;flex-direction:row">
    <div style="width:100px;height:100px;background-color:red;border-color:black;border-style:solid;border-width:2px" :ref="'items'+item" @click="scrollToLeft(item)" v-for="item in list" :key="item"></div>
    <!-- <div :ref="item+'index'">//动态 -->
  </scroller>
</template>

<script>
const dom = weex.requireModule("dom");

export default {
  data() {
    return {
      list: [1,2,3,4,5,6,7,8,10,11,12,13,14,15,16,17,18,19,20],
    };
  },

  mounted() {
 
  },

  methods: {
      //点击向左移动
    scrollToLeft(item) {
 const el = this.$refs[`items${item}`][0];
      console.log(el);
      dom.scrollToElement(el, { offseleft: -100 });
    },
  },
};
</script>

<style  scoped>
</style>

11.animation动画模块

    const el = this.$refs.ref1;  //获取元素
    animation.transition(
              el,
              {
                styles: {
                  transform: "translateX(-228px)",
                  position: "absolute",
                },
                duration: 5000, //ms  持续时间
                timingFunction: "ease-in",   
                delay: 2000, //ms   延时触发
              },
              () => {
                  //动画结束后的回调
              }
            );

12.stream请求模块(接口请求)


在api.js中封装
/* 引入 请求数据模块 */
const stream = weex.requireModule('stream');

/* 配置API接口地址 */
const baseUrl = 'http://192.168.1.107:8080/';

/* 序列化请求方法 */
let toParams=(obj)=>{
    let param = ""
    if(!obj){
        return param;
    }
    for(let name in obj) {
        if(typeof obj[name] != 'function') {
            param += "&" + name + "=" + encodeURI(obj[name])
        }
    }
    return param.substring(1);
}
/* 请求处理函数 */
let ajax=(params={},callFn)=>{
    let ajaxData={
        method:params.method || 'GET',
        type:params.type || 'json',
    }

    if(/http:|https:/.test(params.url)){
        ajaxData.url=params.url;
    }else{
        ajaxData.url=baseUrl+params.url;
    }
    if(ajaxData.method=='GET'){
        ajaxData.url+=('?'+toParams(params.data));
    }else if(ajaxData.method=='POST'||'PUT'){
        //携带请求头
       ajaxData.headers = {
            "Content-Type": "application/json"
        }
        ajaxData.body = JSON.stringify(params.data)
    }
    ajaxData.timeout=30000,

    stream.fetch(ajaxData, (res)=> {
        callFn && callFn(res);
    })
}

/* 暴露对象 */
export default {
    baseUrl,
    ajax
}


 //引用请求接口
 import ApiJs from '../api'

 ApiJs.ajax({
                    url: '',
                    method: 'GET',
                    type: 'text',	//默认 json,默认可以省略
                    //入参
                    data: data,
                }, (res) => {
                    if(res.ok) {
                    //请求成功 
                    }
                })
            },

13.loading加载(建议使用weex-ui组件库)

weex自带的loading加载比较丑,可以使用weex-ui组件库
<template>
    <div>
        <wxc-loading :show="isShow" type="trip"></wxc-loading>
        <wxc-part-loading :show="isShow"></wxc-part-loading>
    </div>
</template>
<script>
    import { WxcLoading, WxcPartLoading } from 'weex-ui';
    export default {
        components: { WxcLoading, WxcPartLoading },
        data () {
            return {
                isShow: true
            };
        }
    };
</script>

14.weex中的坑

1.子绝父相,超出默认隐藏,且修改无效
解决办法:父级盒子写大点

2.weex.config相关配置只能写在js中,不可以在结构中直接进行判断
例如:<div v-if="weex.config.env.platform==='iOS'"></div>  //错误

3.weex中文字溢出不能使用常规的overflow:hidden
解决方法:使用 weex内置的lines
/* 单行溢出省略 */
.overflowEllipsisOne {
  white-space: normal;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 1;
  lines: 1;
  -webkit-box-orient: vertical;
  word-break: break-all;
}


4.只支持px 自带适配  750px标准

5.样式不支持简写,如:
background:red  不支持
必须background-color:red

6.flexbox是默认且唯一的布局,每个元素默认带有display:flex

7.不支持背景图片

8.不支持负边距  z-index 

9.不支持组件缓存

10.ios使用list组件  会造成滑动元素丢失空白问题  建议使用scroller
如果一屏显示,会出现无法滚动问题,可以添加以下属性
alwaysScrollableVertical和alwaysScrollableHorizontal  //横向与纵向滚动 设置为true

11.点击穿透问题
做类似弹窗时点击空白或者弹窗会穿透触发到下面页面的事件,解决方案:在弹窗这些悬浮的父级元素加上@click.stop。
    
12.text末尾标签必须与文字在一行 否则可能会出现样式错乱问题