1.获取屏幕宽高

常规取值

window.onresize = () => {  
    return (() => {    
        window.screenHeight = window.innerHeight;    
        this.screenHeight = window.screenHeight;  
    })()
}

mixins–定义一部分公共的方法或者计算属性,然后混入到各个组件中使用,方便管理与统一修改

const resizeScreen = {  
	data() {    
        return {      
            screenHeight : window.innerHeight,//屏幕高度      
            visibleHeight : window.innerHeight, // 屏幕高度      
            screenWidth : window.innerWidth,//屏幕高度      
            visibleWidth : window.innerWidth, // 屏幕高度    
        }  
    },  
   mounted() {    
       let _this = this;    
       this.$nextTick(() => {      
           window.onresize = function () { // 定义窗口大小变更通知事件        
               return (() => {          
                   window.screenHeight = window.innerHeight;          
                   _this.screenHeight = window.screenHeight;          
                   window.screenWidth = window.innerWidth;         
                   _this.screenWidth = window.screenWidth;        
               })()      
           };    
       })  
   },  
   watch : {    
       screenHeight(val) { //监听屏幕高度变化      
           this.screenHeight = val;      
           this.visibleHeight = this.screenHeight    
       },    
       screenWidth(val) { //监听屏幕高度变化      
           this.screenWidth = val;      
           this.visibleWidth = this.screenWidth    
       },  
   }
};
export default resizeScreen

2.vue阻止事件

click.prevent 阻止默认事件

click.stop 阻止按钮事件冒泡

3.表单验证 、 动态验证

普通跨组件验证

      submitForm() {//子组件验证回调
        return this.$refs.moreintentionRef.validate()
      },
          
      this.$refs.moreIntentionRef.submitForm().then((valid) => {//父组件使用
         if(valid){
            this.dialogVisible = true
          }
      	}, () => {
            this.$message.error("请检查必填项!!!!")
      })

动态表单验证

//data,动态表单数据  
for (let i in data){
   let refName = `dynamicValidateForm${i}`
   let itemName = `Verify${i}`
   this.$refs.addProblemRef.getProblemVerify(refName,itemName)//调用子类问题验证,多表单提交验证,将结果装进数组
  }
      /**
      *@param [refName] [表单ref,动态生成]
      *@param [str][装动态验证值]
      **/
	getProblemVerify(refName,str){//多动态表单验证
           str  =  new Promise((resolve,reject)=>{
            this.$refs[refName][0].validate((valid)=>{
              if (valid) {
                resolve(true)
              } else {
                reject(false)
              }
            })
          })
        this.validateList.push(str)//将验证信息存储
      },
Promise.all(this.$refs.addProblemRef.validateList).then(()=>{//验证Promise生成数据
  //console.log("动态表单验证成功!")
})

4.tabs动态绑定组件、多组件

<el-tabs type="border-card"  v-model="tabindex" tab-position="left" style="margin: 10px" :style="{'height':fullHeight+'px'}" >
    <template v-for="item in tabs"  >
      <el-tab-pane :name="item.dictId" :label="item.label">
        <div style="height: 100%;">
           <component :is=item.content :height="fullHeight" :ref="`ref${item.dictId}`"></component>
         </div>
       </el-tab-pane>
      </template>
 </el-tabs>
 tabs : [
          {
            dictId : '1001',
            label : '客源信息',
            content : 'base-information'//组件名
          },{
            dictId : '1002',
            label : '客配房',
            content : 'c-m-h-index'
          }
     ]

:ref=”ref${item.dictId}动态调用子组件方法使用方法如下:

this.$refs[`ref${this.tabindex}`][0].子组件方法名

5.在滚动条内添加数据让数据想上推动一直显示新添加的数据

在生命周期updated中使用
    updated (){
        this.speechScrollDown()
    },
speechScrollDown(){
  this.$refs['speechScrollbarRef'].wrap.scrollTop =                			     this.$refs['speechScrollbarRef'].wrap.scrollHeight
},

6.实现树组件或者动态组件更换绑定数据属性值

动态表单生成时,element-ui只支持value属性,字段不同时需自行跟换

/**
*@param [content][数据当前的属性]
*@param [value][需要跟换而成的数据]
**/
let keyMap = {
  "content" : "value",
  };
/**
*@param [keyMap][需要跟换属性的json]
*@param [list][需要跟换的数据]
**/
export function attributeReplace(keyMap,list){
  for(let i = 0;i < list.length;i++){
    let obj = list[i];
    for(let key in obj){
      let newKey = keyMap[key];
      if(newKey){
        obj[newKey] = obj[key];
        delete obj[key];
      }
    }
  }
  return list
}

6.对象相互比较看是否相等

/**
*@param [val1][对象1]
*@param [val2][对象2]
*@return boolean
**/
export function objectContrast(val1,val2){
  for (let propName in val1) {
    if (val1.hasOwnProperty(propName) != val2.hasOwnProperty(propName)) return false
    if (typeof val1[propName] != typeof val2[propName]) return false
  }
  for (let propName in val2) {
    if (val1.hasOwnProperty(propName) != val2.hasOwnProperty(propName)) return false
    if (typeof val1[propName] != typeof val2[propName]) return false
    // if(!this.hasOwnProperty(propName)) continue
    if(val1[propName] !== val2[propName]) return false
    if (val1[propName] instanceof Array && val2[propName] instanceof Array) {
      if (!val1[propName].equals(val2[propName])) return false
    } else if (val1[propName] instanceof Object && val2[propName] instanceof Object) {
      if (!val1[propName].equals(val2[propName])) return false
    } else if (val1[propName] != val2[propName]) {
      return false
    }
  }
  return true
}

7.两数组比较是否相等

内容可能是一般数据也可能是Object

/**
 * 比较两个数组是否相等
 * @return boolean
 *@param [val1][数组1]
 * @param [val2][数组2]
 * **/
export function arrayContrast(val1,val2){
  if (val1.length != val2.length) return false
  for (var i = 0, l = val1.length; i < l; i++) {
    if (val1[i] instanceof Array && val2[i] instanceof Array) {
      if (!val1[i].equals(val2[i])) return false
    }else if (val1[i] instanceof Object && val2[i] instanceof Object) {
      if(objectContrast(val1[i],val2[i])){//调用对象比较
        continue
      }else{
        return false
      }
    }else if (val1[i] !== val2[i]) {
      return false
    }
  }
  return true
}

8.动态生成单一表单

内容属性必须是value,验证时可直接使用elemen-ui中form表单方法验证

prop内容显示必须 :prop=”‘domains.’ + index + ‘.value’“格式

动态属性与默认属性不相同时可使用方法6

<el-form :model="dynamicValidateForm" ref="dynamicValidateForm" label-width="40px">
      <el-form-item
        :show-message ='false'
        v-for="(domain, index) in dynamicValidateForm.domains"
        :label="index + 1+'、'"
        :prop="'domains.' + index + '.value'"
        :key="domain.key"
        :rules="{ required: true, message: ' ', trigger: 'blur'}">
        <div style="display: flex;flex-direction: row;width: 100%;">
          <div  class="inputLeft">
            <el-input size="mini"  :autosize="{ minRows: 1, maxRows: 4}" type="textarea" :rows="1" v-model="domain.value"></el-input>
          </div>
          <div class="buttonRight" >
            <div id="buttonright">
              <el-button icon="el-icon-delete" size="mini" type="danger" @click.prevent="removeDomain(domain)"></el-button>
            </div>
          </div>
        </div>
      </el-form-item>
    </el-form>
      removeDomain(item) {//删除
        let index = this.dynamicValidateForm.domains.indexOf(item)
        if (index !== -1) {
          this.dynamicValidateForm.domains.splice(index, 1)
        }
      },

9.动态生成复杂表单并验证

复杂数据验证看方法3

<template v-for="(item,index) in problemArrayList">
      <el-form :model="item" :ref="'dynamicValidateForm'+ index" label-width="40px" class="demo-dynamic form_label_item">
		...内部数据与方法8相同         
      </el-form>
    </template>

10.使用checkbox生成自定义数据并实现选择

v-model=”item.checked” 数据必须

          <template v-for="item in dataList">
            <div>
              <el-checkbox  :value="item"  v-model="item.checked">
                <div style="background-color:#F8F8F8;margin: 5px 15px 0px 15px;">
                  <span class="checkbox_span">
                    
                </span>
                </div>
                </el-checkbox>
            </div>
          </template>

使用计算属性动态生成选中数据

computed : {
      foos(){
        return this.dataList.filter(x => {if(x.checked === true){return true}})//生成数据对象
          //.map可生成数据id
      }
    },

11.区间处理回显数据[大三元]

记录学习

/**
 * 区间处理字段转为显示字符串
 * 面积区间,楼层区间,价格区间处理
 * @param [val1] [区间开始]
 * @param [val2] [区间结束]
 * @param [str] [区间单位]
 * @param [up] [表示无不限]
 * @param [down] [表示以下]
 * @return [返回拼接字符串]
 * @exception/throws [val1,val2] [可缺省]
 * */
export function sectionToString(val1,val2,str,up ='不限',down='以下'){
  let flag1 = ![null, undefined, ''].includes(val1)
  let flag2 = ![null, undefined, ''].includes(val2)
  let sectionstring = flag1 ? flag2 ? typeof val2 === 'string' ? `${val1}${str}~${val2}` : `${val1}-${val2}${str}` : `${val1}${str}~${up}` : flag2 ? `${val2}${str}${down}` : ''
  //代码可读注释|  1 ? { 1t2 ? (1t2t3 ? 1t2t3t : 1t2t3f) : 1t2f } : 1f2 ? 1f2t : 1f2f
  // 1 :val1不为空
  // 2 :val2不为空
  // 3 :typeof val2 === 'string' 判断val2等于字符串
  //1t2 : 条件1为true 并执行条件2
  //1f2 : 条件1为false 并执行条件2
  //1t2t3 : 条件1 2 为true 并执行条件3
  //1t2t3t : 条件1 2 3都为true -------------------------执行结果:50/万元 -不限
  //1t2t3f : 条件1 2 为true 条件三为false---------------执行结果:50-100/万元
  //1t2t : 条件1 2 为true
  //1t2t3t : 条件1 2 3 为true
  //1t2f : 条件1为true 条件2位false--------------------执行结果:50/万元 -不限
  //1f2t : 条件1为false 条件2位true--------------------执行结果:100/万元以下
  //1f2f : 条件1位false 条件2位false-------------------执行结果:null
  return sectionstring
}

12.滚动条触底加载数据[瀑布流,无滚动加载]

其他组件瀑布流加载方式与之一样

组件调用时 v-scrollbar=”scrollbar” [scrollbar]中写具体方法

/**
*el-scrollbar瀑布流触底加载
*/
Vue.directive('scrollbar',{
  bind(el,binding){
    const selectWrap = el.querySelector('.el-scrollbar__wrap');
    selectWrap.addEventListener('scroll', function () {
      if (this.scrollTop !== 0 && this.scrollHeight - this.scrollTop - this.clientHeight === 0) {
        binding.value();
      }
    })
  }
})

13.更改路由数据

import merge from ‘webpack-merge’

this.$router.push({
 	query : merge({},{uuid : uuidC,params : paramsC})
  })

14.自定义命令-鼠标点击别处收起div

export default {
  bind(el,binding,vnode){
    function documentHandler(e){
      if(el.contains(e.target)){
        return false;
      }
      if(binding.expression){
        binding.value(e)
      }
    }
    el._vueClickOutside_ = documentHandler;
    document.addEventListener('click',documentHandler);
  },
  unbind(el,binding){
    document.removeEventListener('click',el._vueClickOutside_);
    delete el._vueClickOutside_;
  }
}

import dropdown from './dropdown'
//用法,需要使用页面路径引入:import elHouseType from '@/directive/el-hosuType'
//页面注册命令:  directives: { elHouseType }
//模块化单独引用,禁止改动
//不全局引用
const install = function(Vue) {
  Vue.directive('clickoutside', dropdown)
}

if (window.Vue) {
  window['clickoutside'] = dropdown
  Vue.use(install); // eslint-disable-line
}
dropdown.install = install
export default dropdown

15.跨几个组件传值[v-bind=”$attrs” v-on=”$listeners”]

祖先组件 `v-on:getHouseList=”getHouseList”

子组件 `v-bind=”$attrs” v-on=”$listeners” ,也可$emit

孙组件`$emit

16.祖先组件直接传值到最底层组件(等找到能响应式更新写上来)

provide: {
      height: 100
  },
inject : ['height'],//接收,使用是直接this.height

17.跨页面验证表单[多页面集于tabs也可使用]

submitForm() {//父组件调用并验证
    return this.$refs.moreintentionRef.validate()
},
 return  new Promise((resolve,reject)=>{//子组件验证后将结果封装传给父组件(适合多种表单子组件公用),只返回验证通过的值,且只有一个参数
        this.$refs.comming.validate((valid)=>{
          if (valid) {
            resolve({flag : true,value : this.commingForm})
          } else {
            this.$message.error("请填写必填项!")
          }
        })
      })
commingFormsubmit(){//父组件配合方法4使用
        this.$refs[`ref${this.tabindex}`][0].submitForm().then((valid)=>{
          switch (this.tabindex) {//
            case "1001":
              this.saveBasicInformation(valid.value)
          }
     })
  }