首页 > 代码库 > vue2.0用法技巧汇总

vue2.0用法技巧汇总

1.class拼接:

技术分享

2.select下拉截取:

<template>
    <!--vip班支付报名页面-->
    <div id="payRecordMain">
        <div class="pay_record_vip">
            <div class="pay_message">报考城市<span class="cityName" v-text="cityName">南京</span></div>
            <div class="pay_message">报考驾照类别
                <span class="getSelectType">
                    <span class="driveTypeText">{{driveType.description}}</span>
                    <select class="exam_type" @change="selectDriveType(driveType)" v-model="driveType">
                        <option v-for="licenseList in vehicleKindPriceVoList" :value="http://www.mamicode.com/licenseList">{{licenseList.description}}</option>
                    </select>
                    <img class="img_arrow" src="http://www.mamicode.com/assets/select_arrow.png" >
                </span>
            </div>
            <div class="pay_message2">
                <span class="baoming">报名费</span>
                <span style="float:right">
                    <span :class="{ling_throught:hasRecommend||(discount&&discount!=‘0‘)}">{{totalPay|formatMoney}}</span> 
                    <span class="totalPayStyle" v-if="hasRecommend||(discount&&discount!=‘0‘)">{{newTotalPay|formatMoney}}</span>
                </span>
            </div>
            <div class="pay_message3" v-if="hasRecommend"><span>通过<span v-text="recommendedName"></span>推荐你使用多伦学车,已为您优惠</span><span v-text="recommendedRelief"></span><span>元</span></div>
            <div class="select">请选择支付方式</div>
            <label for="radio2">
                    <div class="payment">
                        <img src="http://www.mamicode.com/assets/weixinzhifu.png">
                        <span class="pay_text">微信支付</span>
                        <input id="radio2" type="radio" name="radio" value="http://www.mamicode.com/2" checked="checked"/>
                    </div>
                </label>
            <div class="agree">

                <span class="agreeTest1">同意</span>
                <span @click="agree_select()" class="agreeTest2">《支付免责条款》</span>
                <div class="checkboxAgree2" @click="selectInput()" :class="{checkboxAgree2Sel:checkboxAgree2==1}">
                </div>
            </div>
        </div>
        <div class="goPaybuttom_vip">
                <div class="heji">合计:
                    <span v-if="!hasRecommend&&!discount&&discount==‘0‘" class="money2">{{totalPay|formatMoney}}</span>
                    <span v-if="hasRecommend||(discount&&discount!=‘0‘)" class="money2" >{{newTotalPay|formatMoney}}</span>
                </div>
                <div class="submit" @click="goPay()">
                    去结算(1)
                </div>
            </div>
    </div>
</template>
<script>
import Vue from ‘vue‘;
import tool from ‘../common/tools‘;
import httpService from ‘../common/httpService‘;
import commonErr from ‘./CommonErr‘;
import commonToast from ‘../common/commonToast‘;
import {Toast ,Loadmore} from ‘mint-ui‘;
import MessageBox from ‘mint-ui/lib/message-box‘;
import ‘mint-ui/lib/loadmore/style.css‘;
import ‘mint-ui/lib/toast/style.css‘;
import ‘mint-ui/lib/message-box/style.css‘;
import ‘../css/payRecordVip.css‘;

Vue.component(Loadmore.name, Loadmore);
Vue.component(MessageBox.name, MessageBox);
export default {
    data() {
        return {
            hideTime:2000,
            checkboxAgree2:1,//默认免责条款勾选框选中
            driveType:"",//驾照类别,初始C1类型
            settleAccounts:null, 
            payParams:{},
            phoneNum:null, //推荐人电话
            getCount:{},//获取优惠人参数
            getcodeUrl:" ",
            recommendId:" ", //推荐人Id
            recommendPhone:" ", //推荐人号码
            discount:tool.Request(‘discount‘)?tool.Request(‘discount‘):"0 ",//活动优惠金额
            cityName:tool.Request(‘cityName‘), //获取城市名
            vehicleKindPriceVoList:[],//加省略号
            totalPay:0,//结算价格
            hasRecommend:false, //是否有推荐人
            newTotalPay:null,
            recommendedName:" ",//推荐人姓名
            //微信支付 zhw 2016-09-07
            appId:" ",
            timeStamp:" ",
            nonceStr:" ",
            packageValue:" ",
            paySign:" ",
            toGopay:1,
            testCouponsCut:[‘ouIgswP-H4FMZIwsbz8DdCEd0LaM‘],
            valueForWeChats:" ",
            recommendedRelief:"",
            openid:tool.getUrlRequestParam().openid,
            cityClassId: tool.Request(‘cityClassId‘),
        }
        
    },
    components:{
        commonErr:commonErr
    },
    filters:{
        formatMoney : function(money){
            /*var floatNum=parseFloat(money),
                intNum=parseInt(money),
                subtract=floatNum-intNum;
            if(subtract>=0.5){
                subtract=1;
            }else{
                subtract=0;
            }
            money=intNum+subtract;*/
            money=parseFloat(money).toLocaleString();
            return "¥"+money;
          }
    },
    mounted: function() {
        this.payRecordVipMain();
    },
    methods:{
        payRecordVipMain:function(){
            var self=this;
            self.recommendedRelief=tool.Request(‘recommendedRelief‘);
            self.vehicleKindPriceVoList=JSON.parse(decodeURIComponent(tool.Request("vehicleKindPriceVoList")));
            if (window.valueForWeChat) {
                self.valueForWeChats = window.valueForWeChat;
            }
            self.settleAccounts = "/topayServlet";
            self.getcodeUrl =‘/mw/recommendpolite/reliefAmount.do‘;//获取推荐人接口
            
            //渲染当前页面信息
            for(var i=0;i<self.vehicleKindPriceVoList.length;i++){
                var val=self.vehicleKindPriceVoList[i];
                if(val.vehicleKind=="C1"){
                    self.getDescriptions = val.description;
                    self.driveType = val;
                    self.totalPay = val.expense;
                    self.newTotalPay = val.expense;
                    
                    //活动减免
                    if (self.discount) {
                        self.newTotalPay = (Math.round(self.newTotalPay * 100) - Math.round(self.discount * 100)) / 100;//减免后的金额
                        if (self.newTotalPay < 0) {
                            self.newTotalPay = 0;
                        }
                    }
                    
                }
                
                if(val.description.length>0){
                    val.description=val.vehicleKind +"( "+val.description+") ";
                }else{
                    val.description=val.vehicleKind;
                }
            }
            
            //获取推荐人号码参数
            self.getCount = {
                isAchieve:1,
                recommendPhoneNo:"",
                recommendedPhoneNo: self.valueForWeChats.phoneNo,
                needBind: 0,
                type_wc: 2,
            };
              self.getBackRecommendMsg(self.getcodeUrl, self.getCount);
        },
        //获取推荐信息
        getBackRecommendMsg:function (url, params) {
            var self=this;
            httpService.get(url, params).then(function (data) {
                if (data.code != commonToast["MSG_SUCCESS"]) {
                    self.hasRecommend = false;
                    //data.code==1002:没有查询到该手机的相关推荐记录哦
                    if(data.code==1002){
//                      MessageBox.alert(data.msg.then(action => {
//                          self.getRecommend();
//                        });
                    }else{
                        Toast({
                            message:data.msg,
                            position: ‘middle‘,
                            duration:self.hideTime
                        });
                    }
                    return;
                }
                self.hasRecommend = true;
                self.newTotalPay = (Math.round(self.totalPay * 100) - Math.round(self.recommendedRelief * 100))/100;
                if (self.newTotalPay < 0) {
                    self.newTotalPay = 0;
                }

                //活动减免
                if (self.discount) {
                    self.newTotalPay = (Math.round(self.newTotalPay * 100) - Math.round(self.discount * 100)) / 100;//减免后的金额
                    if (self.newTotalPay < 0) {
                        self.newTotalPay = 0;
                    }
                }

                self.recommendId = data.data.recommendId;
                self.recommendPhone = data.data.recommendPhone;
                self.recommendedName = data.data.recommendName;
                
                
            },function(){
                
            })
        },
        
        //下拉框更改时,变更绑定数据
        selectDriveType:function (t) {
//          if(!t){
//              return;
//          }
            var self=this;
            console.log(JSON.stringify(t))
            self.totalPay = t.expense;
            self.newTotalPay = t.expense;
            //self.driveType = t;
            //self.driveType = t.vehicleKind +"( "+t.description+")";
            if (self.hasRecommend) {
                self.newTotalPay = (Math.round(self.totalPay * 100) - Math.round(recommendedRelief * 100))/100;//减免后的金额
                if (self.newTotalPay < 0) {
                    self.newTotalPay = 0;
                }
            }else{
                 self.newTotalPay = self.totalPay;
            }

            //活动减免
            if (self.discount) {
                self.newTotalPay = (Math.round(self.newTotalPay * 100) - Math.round(self.discount * 100)) / 100;//减免后的金额
                if (self.newTotalPay < 0) {
                    self.newTotalPay = 0;
                }
            }

            self.getDescriptions = t.descriptions;
        },
        //弹出免责条款
        agree_select:function () {
            var content = ‘云支付作为网络交易平台,除云支付特定自行销售的产品外,您从云支付上获取的任何产品信息均为云支付用户(包括个人用户及商户)自行发布,云支付对其真实性、合法性及有效性不做任何形式的保证,您应自行判断并承担风险。所有责任由该信息发布者承担。‘;
            MessageBox.alert(content, ‘报名协议‘);
        },
        //点击勾选免责条款
        selectInput:function () {
            var self=this;
            if (self.checkboxAgree2 == 1) {
                self.checkboxAgree2 = 0;
            } else if (self.checkboxAgree2 == 0) {
                self.checkboxAgree2 = 1;
            }
        },
        //去支付按钮事件
        goPay:function () {
            var self=this;
//          debugger;
            if(self.toGopay == 0){
                return;
            }
            if (self.checkboxAgree2 == 1) {
                Toast({
                    message:commonToast["indexLoading"],
                    position: ‘middle‘,
                    duration:self.hideTime
                });
                //接口未通,暂时屏蔽去支付按钮的方法(调测微信支付时放开)
                var pay_params = {
                    studentId: self.valueForWeChats.studentId,
                    paymentType: ‘2‘,
                    stu_account: self.valueForWeChats.phoneNo,
                    cityClassId: self.cityClassId,
                    driveType: self.driveType,
                    totalPay: self.newTotalPay,
                    recommendId: self.recommendId,
                    recommendAccount: self.recommendPhone,
                    openid: tool.getUrlRequestParam().openid,
                };
                self.getBackDate(self.settleAccounts, pay_params);
                //接口未通,暂时屏蔽去支付按钮的方法(调测微信支付时放开)
            } else {
                Toast({
                    message:commonToast["payAgree"],
                    position: ‘middle‘,
                    duration:self.hideTime
                });
            }
        },
        //获取返回的订单信息并通过native调用支付工具
        getBackDate:function(url, params) {
            var self=this;
            httpService.get(url, params).then(function (data) {
                if (data.code == commonToast["MSG_FAILED"]) {
                    //初始化支付控件失败
                    Toast({
                        message: commonToast["payFailInit"],
                        position: ‘middle‘,
                        duration:self.hideTime
                    });
                } else {
                    if(data.flag==2){
                        //您已支付成功,不要重复支付
                        Toast({
                            message: commonToast["payRepeat"],
                            position: ‘middle‘,
                            duration:self.hideTime
                        });
                        return;
                    }
                    self.appId = data.appid;
                    self.timeStamp = data.timeStamp;
                    self.nonceStr = data.nonceStr;
                    self.packageValue = data.package;
                    self.paySign = data.sign;
                    WeixinJSBridge.invoke(‘getBrandWCPayRequest‘, {
                        "appId": appId,
                        "timeStamp": timeStamp,
                        "nonceStr": nonceStr,
                        "package": packageValue,
                        "signType": "MD5",
                        "paySign": paySign
                    }, function (res) {
                        //                      alert(res.err_msg);
                        //                      alert(res.err_code + res.err_desc + res.err_msg);
                        if (res.err_msg == "get_brand_wcpay_request:ok") {
                            MessageBox.alert(commonToast["paySuccess"]).then(action => {
                                //支付成功 回到首页
                                var url = "indexTab/index",
                                    params={
                                        openid:tool.getUrlRequestParam().openid,
                                    };
                                tool.goUrl(url,params);
                            });
                        } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                            //取消支付!
                            Toast({
                                message:commonToast["payCancel"],
                                position: ‘middle‘,
                                duration:self.hideTime
                            });
                        } else {
                            //alert("支付失败");
                            //支付失败!
                            Toast({
                                message:commonToast["payFail"],
                                position: ‘middle‘,
                                duration:self.hideTime
                            });
                        }
                    })
                }
            },function(){
                
            });
            $http({
                method: "get",
                url: url,
                params: params
            }).success(function (data) {
                $ionicLoading.hide();
                if (data.code == 0) {
                    $ionicLoading.show({
                        template: "初始化支付控件失败..."
                    });
                    $timeout(function () {
                        $ionicLoading.hide()
                    }, 3000);
                } else {
                    if(data.flag==2){
                        $ionicLoading.show({
                            template: "您已支付成功,不要重复支付"
                        });
                        $timeout(function () {
                            $ionicLoading.hide()
                        }, 3000);
                        return;
                    }
                    appId = data.appid;
                    timeStamp = data.timeStamp;
                    nonceStr = data.nonceStr;
                    packageValue = data.package;
                    paySign = data.sign;
                    WeixinJSBridge.invoke(‘getBrandWCPayRequest‘, {
                        "appId": appId,
                        "timeStamp": timeStamp,
                        "nonceStr": nonceStr,
                        "package": packageValue,
                        "signType": "MD5",
                        "paySign": paySign
                    }, function (res) {
                        //                      alert(res.err_msg);
                        //                      alert(res.err_code + res.err_desc + res.err_msg);
                        if (res.err_msg == "get_brand_wcpay_request:ok") {
                            defineAlert("支付成功!", function () {
                                //微信支付成功后,做业务处理
                                var url = "indexTab/index",
                                    params={
                                        openid:tool.getUrlRequestParam().openid,
                                    };
                                tool.goUrl(url,params);
                                //var url = valueForWeChat.html5BaseUrl + "/stu/stu_index.html?openid="+openid +"#/index";
                            },true);

                        } else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                            defineAlert("取消支付!", function () {
                              
                            });
                        } else {
                            //alert("支付失败");
                            defineAlert("支付失败", function () {
                                
                            });
                        }
                    })
                }
            }).error(function () {
                $ionicLoading.show({
                    template: "初始化支付控件失败..."
                });
                $timeout(function () {
                    $ionicLoading.hide()
                }, 3000);
            });
        },
        //获取优惠
//      getRecommend:function () {
//          var alertStr = ‘<div id="J_alert" class="grayBackground" style="z-index:10">‘ + ‘<div class="dialogCover"></div>‘ + ‘<div class="dialog-div">‘ + ‘<div class="dialog">‘ + ‘<div class="phoneTest">请输入推荐人手机号码</div>‘ + ‘<div class="inputPhone"><input class="inputValue" type="text" maxlength="11"></div>‘ + ‘<div class="btn-bar">‘ + ‘<div class="btn-bar-inner">‘ + ‘<div class="btn-alert-single confirmButton-blue-border" id="J_btn_alert_ok">确定</div>‘ + ‘</div></div></div></div></div>‘;
//          if ($("#J_alert").length) {
//              $("#J_alert").remove();
//          }
//          $("body").append(alertStr);
//          dialog_re_adapt(100);
//          dialog_re_adapt(200);
//          dialog_re_adapt_but(100);
//          $("#J_btn_alert_ok").click(function () {
//              //点击确定时获取输入框的值并传给后台
//              phoneNum = $(".inputValue").val();
//              getCount = {
//                  recommendPhoneNo: phoneNum,
//                  recommendedPhoneNo: valueFromNativeAll.phoneNo,
//                  type_wc: 2,
//                  openid: openid,
//                  needBind: 1
//              };
//              getcode_url = valueFromNativeAll.serverBaseUrl + ‘/mw/recommendpolite/reliefAmount.do‘;
//              var real = checkPhone();
//              if (!real) {
//                /*  defineAlert2(‘手机号码格式不正确哦!请您重新输入‘, function () {
//                      self.getRecommend();
//                  });*/
//                  $ionicLoading.show({
//                      template: ‘手机号码格式不正确哦!请您重新输入‘
//                  });
//                  setTimeout(function () {
//                      $ionicLoading.hide();
//                  }, autoHideTime);
//              } else {
//                 // $("#J_alert").hide();
//                  $("#J_alert").remove();
//                  getBackRecommendMsg(getcode_url, getCount);
//              }
//              // $("#J_alert").hide();
//          });
//          $(".dialogCover").click(function () {
//              //$("#J_alert").hide();
//              $("#J_alert").remove();
//          });
//
//          function dialog_re_adapt(e) {
//              !e ? e = 0 : "";
//              setTimeout(function () {
//                  var e = $(window).height(),
//                      t = $(".dialog-div").height();
//                  $(".dialog-div").css("top", (e - t) / 2 + "px")
//              }, e)
//          }
//
//          function dialog_re_adapt_but(e) {
//              !e ? e = 0 : "";
//              setTimeout(function () {
//                  var e = $(window).height(),
//                      t = $(".goPaybuttom_vip").height();
//                  $(".goPaybuttom_vip").css("top", (e - t)+ "px");
//                  $(".dialogCover").css("height", e+ "px");
//              }, e)
//          }
//
//          return false;
//      },
        
    },
}
</script>

 

 

 

3.实时监听input的value值,vue中虽然有和angular双向数据绑定ng-model一样功能的指令v-model,但是并不能实时监听,而@change也不能实时对input的value值进行实时运行,后来找到一个watch方法能实时监听,并实时响应,api路径:https://vuefe.cn/v2/api/#vm-watch

代码如下:

<template>
    <div id="baiduSearchMain">
        <div id="r-result" class="pr">
            <div class="pa imputWrap">
                <input type="text" id="suggestId"  v-model="inputAdd" size="20"
                       value="" placeholder="请输入关键字" class="searchIpt"/>
                <img src="http://www.mamicode.com/assets/icon_search.png"/>
            </div>
        </div>
        <div class="currentAddress">
            <div class="AddressT">当前位置</div>
            <div class="row">
                <div class="currentAddressD" @click="backToPrePage()">{{currentAddress}}</div>
                <div class="currentAddressGdp" @click="resetLocation()"><img src="http://www.mamicode.com/assets/icon_locationg.png" alt="重新定位"/>
                    <div id="allmap" style="display:none;"></div>
                </div>
            </div>
        </div>
        <div class="fujinAddress">
            <div class="AddressT">附近地址</div>
            <div class="AddressC">
                <div class="fujinAddressDetail" @click="getAddress(index)" v-for="(addressDes,index) in address">
                    <p><img src="http://www.mamicode.com/assets/icon_location.png"/><span>{{addressDes.title}}</span></p>
                </div>
            </div>
        </div>
    </div>
</template>
<script>
import Vue from ‘vue‘;
import tool from ‘../common/tools‘;
import httpService from ‘../common/httpService‘;
import commonToast from ‘../common/commonToast‘;
import ubderscore from ‘../common/underscore-min.js‘;
import {Toast ,Loadmore} from ‘mint-ui‘;
import MessageBox from ‘mint-ui/lib/message-box‘;

import ‘mint-ui/lib/loadmore/style.css‘;
import ‘mint-ui/lib/toast/style.css‘;
import ‘mint-ui/lib/message-box/style.css‘;
import ‘../css/baiduSearch.css‘;

Vue.component(Loadmore.name, Loadmore);
Vue.component(MessageBox.name, MessageBox);
export default {
    data() {
        return {
            currentAddress:tool.Request("currentAddress"),
            gps:tool.Request(‘gps‘),
            ac:null,
            timer:null,
            currentPoint:null,
            map:null,
            address:[],//地址列表
            hideTime:2000,//隐藏弱提示时间
            inputAdd:""
//          time:0,
        }
    },
    watch:{
        inputAdd: function (curVal,oldVal){
//      console.log(curVal,oldVal);
            if(this.ac){
                this.ac.search(this.inputAdd);
            }
    }
    },
    mounted: function() {
        this.baiduSearchMain();
    },
    methods:{
        //主函数
        baiduSearchMain:function(){
            var self=this;
            var arr = this.gps.split(",");
            var currentPoint = new BMap.Point(parseFloat(arr[1]), parseFloat(arr[0]));
            this.map = new BMap.Map(‘allmap‘);
            this.map.centerAndZoom(currentPoint, 16);
            
             this.ac = new BMap.LocalSearch(this.map, ( //建立一个自动完成的对象
                {
                    "onSearchComplete": function () {
                        var result = self.ac.getResults();
                        if (result) {

                            self.address = result.xr;

                            self.address = ubderscore.uniq(self.address, function (item) {
                                return item.title;
                            });
                            console.log(self.address);
                        }
                    },
                    "pageCapacity": 20
                }));
            this.ac.search(this.currentAddress);
        },
        //附近地址
        reSearchLocation:function (e) {
        
            console.log(e.target.value)
            this.value =http://www.mamicode.com/ e.target.value;
            this.ac.search(e.target.value);
        },
        //返回上一页
        backToPrePage:function () {
            window.history.back();
        },
        getAddress:function (index) {
            window.history.back();
//          var stop=setInterval(function(){

//              this.time++;
//              if(this.time>4){
//                  this.time=0;
//                  window.history.back()
//              }
//              console.log(this.time)
//          }, 100);
            localStorage.setItem(‘location‘, JSON.stringify({
                ‘address‘: this.address[index].title,
                ‘gps‘: this.address[index].point.lat + ‘,‘ + this.address[index].point.lng
            }));
            //setTimeout(window.history.back(),3000);
        },
        //重新定位
        resetLocation:function () {
            var self=this;
            Toast({
                message: commonToast["baiduSeaLocation"],
                position: ‘middle‘,
                duration:self.hideTime
            });
            var geolocation = new BMap.Geolocation();
            geolocation.getCurrentPosition(function(r){
                if(this.getStatus() == BMAP_STATUS_SUCCESS){
                    var mk = new BMap.Marker(r.point);
                    var latitude = r.point.lat;
                    var longitude = r.point.lng;
                    this.gps = latitude + "," + longitude;
                    
                    var pt = r.point;
                    console.log(‘您的位置:‘+r.point.lng+‘,‘+r.point.lat);
                    var geocoder = new BMap.Geocoder();
                    var currentPoint = r.point;
                    geocoder.getLocation(currentPoint, function (result) {
                        self.currentAddress = result.address;
                        localStorage.setItem(‘location‘, JSON.stringify({
                            ‘address‘:result.address,
                            ‘gps‘: self.gps
                        }));
                        self.ac.search(self.currentAddress);
                    });
                }else {
                    this.currentAddress = "南京市";
                    localStorage.setItem(‘location‘, JSON.stringify({
                        ‘address‘: "南京市",
                        ‘gps‘: "32.0572355,118.77807441"
                    }));
                }        
            },{enableHighAccuracy: true})
            
        },
    }
}
</script>

 

vue2.0用法技巧汇总