vue项目笔记

vue-axios跨域使用
在config.index.js设置本地代理

 dev: {
   // Paths
   assetsSubDirectory: 'static',
   assetsPublicPath: '/',
   proxyTable: {
     '/api': {
       target: 'http://192.168.5.207:8080',
       //http://192.168.5.207:8080本地
       changeOrigin: true,
       pathRewrite: {
         '^/api': '/'
       }
     }
   },

在config.dev.env.js设置开发接口

'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')

module.exports = merge(prodEnv, {
  NODE_ENV: '"development"',
  API_HOST:"/api/"
})

在config.prod.env.js设置生产接口

'use strict'
module.exports = {
  NODE_ENV: '"production"',
  API_HOST:'"http://117.78.48.244/testapi/"'
}
//mian.js引入axios
//引入axios并改写原型链
import axios from 'axios'
Vue.prototype.$ajax = axios;

vue img标签数据定义


单选框组件




.cbox{display:block;width:16px;height:16px;border:1px solid #ccc;background:#fff;position: relative;} .cbox.checked{background:#10adff;}
 .cbox.checked:after{content:"√";color: #FFFFFF;position: absolute;left: 2px;top: -3px;}

cookie操作

//存入cookie
setCookie(name, value, time) {
  var strsec = this.getsec(time);
  var exp = new Date();
  exp.setTime(exp.getTime() + strsec * 1);
  document.cookie = name + "=" + value + ";expires=" + exp.toGMTString();
},
//设置过期时间
getsec(str) {
  // alert(str);
  var str1 = str.substring(1, str.length) * 1;
  var str2 = str.substring(0, 1);
  if (str2 == "s") {
    return str1 * 1000;
  }
  else if (str2 == "h") {
    return str1 * 60 * 60 * 1000;
  }
  else if (str2 == "d") {
    return str1 * 24 * 60 * 60 * 1000;
  }
},
//删除cookies
function delCookie(name)
{
  var exp = new Date();
  exp.setTime(exp.getTime() - 1);
  var cval=getCookie(name);
  if(cval!=null)
    document.cookie= name + "="+cval+";expires="+exp.toGMTString();
}
//获取cookies
function getCookie(name) {
  var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
  if (arr = document.cookie.match(reg))
    return arr[2];
  else
    return null;
}

优化文件上传标签


 

上传文件

// 将文件以Data URL形式进行读入页面
         // 上传图片判断
      readAsDataURL() {
     var _this = this;
        const imagesLength = document.querySelectorAll('#result > img');
        //判断img的length
        if (imagesLength.length === 9) {
          this.$alert('最多添加9张', '', {
            confirmButtonText: '确定',
            callback: action => {
              return
            }
          });
        } else {
          const image = document.getElementById("video");
          const point = image.value.lastIndexOf(".");
          const type = image.value.substr(point);
          const result = document.getElementById('result');
          // console.log(image.files[0].size);
          //不能为空
          if (image.value == "") {
            return
          }
          // 检查是否为图像类型
          if (type == ".gif" || type == ".GIF" || type == ".jpg" || type == ".jpeg" || type == ".JPG" || type == ".JPEG" || type == ".PNG" || type == ".png") {
            if (image.files[0].size > 512000) {
              return this.$message('图片尺寸请不要大于500KB');
            } else if (image.files[0].size === undefined) {
              return
            }
          } else {
            return this.$message('只能输入jpg/gif/png格式的图片');
          }
          // console.log(2);
          const file = image.files[0];
          const param = new FormData(); //创建form对象
          param.append('video', file);//通过append向form对象添加数据
          const config = {
            headers: {'Content-Type': 'multipart/form-data'}
          };  //添加请求头
          let user = process.env.API_HOST + 'managementimagecontroller/addzhibotu';
          _this.$ajax.post(user, param, config)
            .then(res => {
              // console.log("成功");
              // console.log(res);
              let images = new Image();
              images.src = res.data.dataMap.url;
              images.style.width = "10%";
              images.style.height = "10%";
              images.style.marginLeft = '14px';
              result.appendChild(images);
            })
        }
      },

vuex下载:cnpm install vuex --save
vuex目录


vue项目笔记_第1张图片
1516444032(1).jpg

index.js

//vuex入口文件
import state from './state.js'
import mutations from './mutations.js'
import getters from './getters.js'
export default {
  state:state
  // mutations:mutations,
  // getters:getters
}

state.js

//定义共享的状态数据等等
let state={
  //切换工作账户的dataMap
  againLoginDataMap:"",
  //家庭医生我的用户于共享参数
  count:"",
  //家庭医生服务设置于共享参数
  postion:"",
  //家庭医生服务设置于共享参数
  serverSa:[],
//  家庭医生用户订单产品uuid
  productUuid:"",
  //  家庭医生服务设置服务名称
  serviceName:"",
  //  家庭医生服务设置跳转二级页面所需要的参数
  serverTwo:"",
  //家庭医生直播课件案列跳转编辑页面所需要的参数
  serviceSetList:[],
//  注册时验证码
  registerImag:"",
  //  注册时密码
  registerPwa: "",
//  注册时手机号
  registerIphone: "",
//  注册时手机验证码
  registerIphoneCode: "",
//  注册时生成的唯一标识
  registersessionId:"",
  //将登陆返回的customerUuid赋值
  customerUuid:"",
//  切换工作账户时需要的账号
  againUserName:"",
  //  切换工作账户时需要的密码
  againUserPwa:"",
  //商品SkuNo
  skuNo: "",
  //供应商名称
  supplierName: "",
  //供应商uuid
  storeUuid: "",
  //仓库编号
  warehouseNo: "",
  //平台分类uuid
  categoryUuid: "",
}
export default state;

mutations.js

//可以更改state定义的状态
import state from './state.js'
export default{
  // increment(state,num){
  //   state.count += num;
  // },
  // reduce(state,num){
  //   state.count -= num;
  // },
  // addgoodslist(state,obj){
  //   state.goodslist.push(obj);
  // }
}

actions.js

// 可以修改mutations

getters.js

//可以理解为vuex的计算属性带有缓存
// export default {
//   count:(state)=>{
//     return state.count;
//   }
// }

//mian.js引入
//引入vuex
import Vuex from 'vuex';
//实例化vuex
Vue.use(Vuex);
//引入vuex入口文件index
import storeObj from '@/store/index';
let store =new Vuex.Store(storeObj);
// console.log(store);
Vue.config.productionTip = false;
// import '../static/utf8-jsp/jsp/config';
/* eslint-disable no-new */
new Vue({
  el: '#app',
  router,
  store,
  template: '',
  components: { App }
})

接口参数加密需要kay和iv,后端java自己搞的前段只加密

//导出公共方法
export {getAesString}
function getAesString(data,key,iv){//加密
  var key  = CryptoJS.enc.Utf8.parse(key);
  var iv   = CryptoJS.enc.Utf8.parse(iv);
  var encrypted =CryptoJS.AES.encrypt(data,key,
    {
      iv:iv,
      mode:CryptoJS.mode.CBC,
      padding:CryptoJS.pad.Pkcs7
    });
  return encrypted.toString();    //返回的是base64格式的密文
}
let data = {
          customerUuid: _this.cookieUuid.customerUuid,
          sessionId: _this.cookieUuid.sessionId,
          tokenId: _this.cookieUuid.tokenId
        };
        let dateJson = JSON.stringify(data);
        let akey = 'smkldospdosldaaa';  //密钥
        let aiv = '0392039203920300';  //iv
        let encrypted = getAesString(dateJson, akey, aiv); //密文
        // console.log(encrypted);
        let user = process.env.API_HOST + 'appwocao';
        this.$ajax({
          method: 'post',
          url: user,
          params: {
            "requestStr": encrypted
          }
        })

获取机器码
// 获取机器码

generateUUID() {

var d = new Date().getTime();

var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,function(c) {

var r = (d + Math.random()*16)%16 | 0;

d = Math.floor(d/16);

return (c=='x' ? r : (r&0x3|0x8)).toString(16);

});

return uuid;

}

文本超出隐藏显示....

.textt{

display:block;

/*显示两行多余的....表示*/
    text-overflow: -o-ellipsis-lastline;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;

}

element ui 日历限制选择范围



// 情景1: 设置选择今天以及今天之后的日期
data (){
   return {
       pickerOptions0: {
          disabledDate(time) {
            return time.getTime() < Date.now() - 8.64e7;
          }
        },  
   }     
}    
// 情景2: 设置选择今天以及今天以前的日期
data (){
   return {
       pickerOptions0: {
          disabledDate(time) {
            return time.getTime() > Date.now() - 8.64e6
          }
        },  
   }     
}   
//  情景3: 设置选择今天之后的日期(不能选择当天时间)
data (){
   return {
       pickerOptions0: {
          disabledDate(time) {
            return time.getTime() < Date.now();
          }
        },  
   }     
}    
// 情景4: 设置选择今天之前的日期(不能选择当天)
data (){
   return {
       pickerOptions0: {
          disabledDate(time) {
            return time.getTime() > Date.now();
          }
        },  
   }     
}    
// 情景5: 设置选择三个月之前到今天的日期
data (){
   return {
       pickerOptions0: {
          disabledDate(time) {
            let curDate = (new Date()).getTime();
            let three = 90 * 24 * 3600 * 1000;
            let threeMonths = curDate - three;
            return time.getTime() > Date.now() || time.getTime() < threeMonths;;
          }
        },  
   }     
} 
// 两个输入框




ata(){
    return {
         pickerOptions0: {
                disabledDate: (time) => {
                    if (this.value2 != "") {
                        return time.getTime() > Date.now() || time.getTime() > this.value2;
                    } else {
                        return time.getTime() > Date.now();
                    }

                }
            },
            pickerOptions1: {
                disabledDate: (time) => {
                    return time.getTime() < this.value1 || time.getTime() > Date.now();
                }
            },
    }      

鼠标事件

Mouseover:不论鼠标指针穿过被选元素或其子元素,都会触发 mouseover 事件。
Mouseenter:只有在鼠标指针穿过被选元素时,才会触发 mouseenter 事件。
mouseout:不论鼠标指针离开被选元素还是任何子元素,都会触发 mouseout 事件。
mouseleave :只有在鼠标指针离开被选元素时,才会触发 mouseleave 事件。

element ui tree获取选中的id
首先修改下element-ui.common.js里的

TreeStore.prototype.getCheckedKeys = function getCheckedKeys() {
    var leafOnly = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;

    var key = this.key;
    var allNodes = this._getAllNodes();
    var keys = [];
    allNodes.forEach(function (node) {
      if (!leafOnly || leafOnly && node.isLeaf) {
        if (node.checked||node.indeterminate) {//这里
          keys.push((node.data || {})[key]);
        }
      }
    });
    return keys;
  };

//页面
 
          
          通过 key 获取
       data2: [{
          id: 1,
          label: '一级 1',
          children: [{
            id: 4,
            label: '二级 1-1',
            children: [{
              id: 9,
              label: '三级 1-1-1'
            }, {
              id: 10,
              label: '三级 1-1-2'
            }]
          }]
        }, {
          id: 2,
          label: '一级 2',
          children: [{
            id: 5,
            label: '二级 2-1'
          }, {
            id: 6,
            label: '二级 2-2'
          }]
        }, {
          id: 3,
          label: '一级 3',
          children: [{
            id: 7,
            label: '二级 3-1'
          }, {
            id: 8,
            label: '二级 3-2'
          }]
        }],
        defaultProps: {
          children: 'children',
          label: 'label'
        }

//vue 利用v-bimd实现点击旋转的效果

 
                  >
  
export default {
    data(){
      return{
        ishow: false
    },


获取elemenui el-checkbox选中的值

  
 
data(){
return:{
  checkList:[]
}
//JS
 //获取复选框的值
      checkinlist(){
        console.log(this.checkList);
      }

js待确认框

 if (confirm("你确定提交吗?")) {
          alert("点击了确定");
        }
        else {
          alert("点击了取消");
        }

js输入框

let causeThawing = prompt("解冻原因");
       if (causeThawing){
        }else{
}

// 字母排序

var arr =[
    {customerName:'v'}
   {customerName:'b'}
   {customerName:'a'}
]
 sortbCustomerInfoModelList(name){
        return function(o, p){
          var a, b;
          if (typeof o === "object" && typeof p === "object" && o && p) {
            a = o[name];
            b = p[name];
            if (a === b) {
              return 0;
            }
            if (typeof a === typeof b) {
              return a < b ? -1 : 1;
            }
            return typeof a < typeof b ? -1 : 1;
          }
          else {
            throw ("error");
          }
        }
      }

arr.sort(sortbCustomerInfoModelList('customerName'))

============select获取选中

 let sectProvinceIndex = document.getElementById("sectProvince").selectedIndex;//获得省第几个被选中了
      console.log(document.getElementById("sectProvince").options[sectProvinceIndex].text);

//后端返回数组[i]是字符串,将数组[i]转为对象分别push到dtypes

            for (let i = 0; i < res.data.dataMap.dtypes.length;i++){
            _this.dtypes.push(eval("("+res.data.dataMap.dtypes[i]+")"));
            }
            console.log( _this.dtypes);

//vuecli全局loding

/**
 * http配置
 */
// 引入axios以及element ui中的loading和message组件
import axios from 'axios'
import { Loading, Message } from 'element-ui'
// 超时时间
axios.defaults.timeout = 5000
// http请求拦截器
var loadinginstace
axios.interceptors.request.use(config => {
  // element ui Loading方法
  loadinginstace = Loading.service({ fullscreen: true })
  return config
}, error => {
  loadinginstace.close()
  Message.error({
    message: '加载超时'
  })
  return Promise.reject(error)
})
// http响应拦截器
axios.interceptors.response.use(data => {// 响应成功关闭loading
  loadinginstace.close()
  return data
}, error => {
  loadinginstace.close()
  Message.error({
    message: '加载失败'
  })
  return Promise.reject(error)
})

export default axios

//引奇葩第三方日历

function scripts() {
$("body").append(
 '' +
 ''
)
}
export { //很关键
scripts
}

import {scripts} from '../../../static/js/asd'
mounted() {
   scripts();
 },

//优化复选框显示


/*隐藏复选框*/
  .my_protocol .input_agreement_protocol {
    appearance: none;
    -webkit-appearance: none;
    outline: none;
    display: none;
  }

  /*未选中时*/
  .my_protocol .input_agreement_protocol + span {
    width: 14px;
    height: 14px;
    border: 1px solid #e3e3e3;
    background-color: #10adff;
    display: inline-block;
    background: url(../../../static/images/duigou.png) no-repeat;
    background-position-x: 0px;
    background-position-y: -25px;
    position: relative;
    top: 3px;
  }

  /*选中checkbox时,修改背景图片的位置*/
  .my_protocol .input_agreement_protocol:checked + span {
    background-position: 0 0px
  }

你可能感兴趣的:(vue项目笔记)