常见需求

431 阅读8分钟

本文正在参加「金石计划」 ” 掘金·金石计划

根据后台返回的字段展示不同的文字

多层判断

{{item.rentalStatus === 0 ? '空' : item.rentalStatus === 1 ? '租'
             :item.rentalStatus === 2 ? '维' : '定'}}

复制文字

blog.csdn.net/sugerinafla…

vscode - 双击选不中

image.png

_sss 类似于这种就可以选中

vscode配置:双击选中连字符

image.png 通过Command +shift+p打开命令面板,使用如下命令,打开vscode配置文件

Preferences: Open User Settings

搜索

在搜索中输入editor.wordSeparators,找到需要的字符,将其删除,保存就行了。

data中拿到props的值

image.png

image.png 不带:是字符串

输入的只能是正整数 elementUI + vue 输入框只能输入正整数 不能输入字母 e 以及+ - 号

image.png

onKeyDown-输入前

在用户按下任何键盘键(包括系统按钮,如箭头键和功能键)时发生。、

image.png

 <el-input type="number" onkeypress="return(/[\d]/.test(String.fromCharCode(event.keyCode)))" placeholder="请输入正整数" class="input-num" clearable size="small" v-model.trim="ruleForm.discountRatioRight"></el-input>

rules写错了

scss & 的用法

image.png

      // this.$notify({
      //   title: "选择的数据",
      //   message: `一共选择了${data.length}条数据`,
      //   duration: 4500,
      //   type: "success",
      //   position: "bottom-right",
      // });

yarn的项目 用cnpm 下载依赖回报一些esline的错误

js 判断是不是数值 包含0 排除undefined

需要把node_module 删除重新跑 yarn i 是不行的 需要yarn install

yarn dev ok了

监听鼠标滚轮 屏幕缩放事件

    
    mounted () {
  window.addEventListener('keyup',this.handleKeyup)
  window.addEventListener('scroll',this.handleScroll)
 }

 destroyed () {
 window.removeEventListener('keyup',this.handleKeyup)
  window.removeEventListener('scroll',this.handleScroll)
  },

拿到隐藏的class

 let styleElement = document.getElementsByClassName('el-card__body')[0];
        styleElement.style.cssText = 'height:calc(100vh - 85px);';
  
  
  
let styleElement = document.getElementsByClassName('el-card__body')[0];
        styleElement.style.cssText = 'height:100vh;';
        console.log('styleElement', styleElement);

修改样式

    // this.$refs.allBox.$el.style.cssText =
   
   
   
   

图片需要往上移动

image.png

父元素定位 子元素 top负值

js动态添加删除样式

  // 拖拽类型  开始拖拽一个元素时触发
    dragStart(e) {
      if (document.getElementsByClassName('itemDiv').length > 0) {
        let allBoxDiv = document.getElementsByClassName('itemDiv');
        // allBoxDiv.forEach((item,index)=>{
        //    item.classList.remove("editorArea");
        // })
        // 2.采取遍历 依次打印里面的元素对象
        // for(var i = 0; i < allBoxDiv.length; i++){
        //     console.log(allBoxDiv[i]);
        //    allBoxDiv[i].classList.add("all-events-none");
        //  }
        // for(var i = 0; i < allBoxDiv.length; i++){
        //     console.log(allBoxDiv[i]);
        //   //  allBoxDiv[i].classList.add("all-events-none");
        //    allBoxDiv[i].classList.remove("pointer-events");
        //  }
        if (this.currentRegionIndex !== null) {
          //  allBoxDiv[this.currentRegionIndex].classList.add("all-events-none");
          this.$nextTick(() => {
            allBoxDiv[this.currentRegionIndex].classList.remove(
              'pointer-events'
            );
          });
        }
      }

      // console.log("this.type", e.target.dataset.type); //  images  product  images  dataset  这个参数哪来的?dataset: DOMStringMap {type: "images"}
      /* 拖拽组件开始的时候就开始赋值了 */
      this.type = e.target.dataset.type;
    },
    // 左边挪到右边结束时触发
    dragEnd(e) {
      console.log('结束拖拽this.index', this.index);
      this.$delete(this.view[this.index], 'status');
      this.isPush = false;
      this.type = null;
      if (document.getElementsByClassName('itemDiv').length > 0) {
        //  document.getElementsByClassName("itemDiv").classList.remove("all-events-none");
        //  document.getElementById("itemDiv").classList.add("editorArea");
        let allBoxDiv = document.getElementsByClassName('itemDiv');
        //  for(var i = 0; i < allBoxDiv.length; i++){
        //     console.log(allBoxDiv[i]);
        //    allBoxDiv[i].classList.remove("all-events-none");
        //  }

        //  for(var i = 0; i < allBoxDiv.length; i++){
        //     console.log(allBoxDiv[i]);
        //   //  allBoxDiv[i].classList.remove("all-events-none");
        //    allBoxDiv[i].classList.add("pointer-events");
        //  }
        if (this.currentRegionIndex !== null) {
          allBoxDiv[this.currentRegionIndex].classList.add('pointer-events');
        }
      }
    },

key 报错

vue.runtime.esm.js:619 [Vue warn]: Duplicate keys detected: 'NaN'. This may cause an update error...

www.jianshu.com/p/1e203ba46…

更改后:(加了一个前缀index处理)

 <el-breadcrumb-item
        v-for="(item, index) in levelList"
        :key="index + item.path" 
      >

这里需要注意的是 el-submenu也是需要加上index的不然会报错

image.png

image.png

  <el-submenu :index="threeItem.id + ''">
                      <span slot="title">{{ threeItem.displayName }}</span>
                      <el-menu-item
                        v-for="(fourItem, fourIndex) in threeItem.children"
                        :key="fourIndex + fourItem.route"
                        :index="
                          '/' +
                            oneItem.route +
                            '/' +
                            towItem.route +
                            '/' +
                            threeItem.route +
                            '/' +
                            fourItem.route
                        "
                        >{{ fourItem.displayName }}</el-menu-item
                      >
                    </el-submenu>

github.com/ElemeFE/ele…

看到网友说才知道 因为已经加了el-menu-item上的index 还报找不到这个错误 image.png

关闭弹层不要只用这个了清空值

     this.$refs[formName].resetFields(); 

image.png .resetFields() 只做那个清空校验!!! image.png

element ui中的select 下拉出现蓝色字体解决

image.png

image.png

image.png

数据生成器

image.png

image.png

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    const createValues = (creator,length = 10) => Array.from({length},creator)
    function createUser(v,index){
      return {
        name:`user-${index}`,
        age:Math.random() * 100 >> 0
      }
    }
    const user = createValues(createUser,100)
    console.log("user:",user);
  </script>
</body>
</html>

slot-scope是作用域插槽

官网中有一句特别强调的话:父组件模板的所有东西都会在父级作用域内编译;子组件模板的所有东西都会在子级作用域内编译。简单的所,就是父组件中不能直接用自组件中定义的data数据。而slot-scope的出现就是解决了这样的问题。

也就是说父组件要使用子组件中的数据!!!

如下代码:

父组件:

<template lang="">
  <div>
    <h3>这是父组件</h3>
    <son>
      <template slot="myslot" slot-scope="scope">
        <ul>
          <li v-for="item in scope.data">{{item}}</li>
        </ul>
      </template>
    </son>
  </div> 
</template>

子组件:

<template>
  <div>
    <h4>这是子组件</h4>
    <input type="text" placeholder="请输入">
    <slot name="myslot" :data='list'></slot>
  </div>
</template>
 
<script>
  export default {
    name:'Son',
    data(){
      return{
        list:[
          {name:"Tom",age:15},
          {name:"Jim",age:25},
          {name:"Tony",age:13}
        ]
      }
    }
  }
</script>

image.png

其中,下方三个对象的值,我们本身是在子组件中定义的,按照官方文档中说的,本来父组件中是无法显示出来这些数据的,但是为什么现在显示出来了呢???这就要归功于我们强大的slot-scope了。

首先,在子组件中的插槽上有一句data="list",而在父组件中也有slot-scope="scope",slot-scope就是取data的值,slot-scope的值是自定义的,我们可以取任何名称,但是data的值传过来时是以对象形式传输的,所以在这scope.data才是list的值。

vue事件阻止冒泡

@click.stop

flex 设置子盒子的width 不允许撑开

image.png

同时设置flex和width:0,确保宽度不会被撑开

如果没有设置width,当内部元素的内容大小超过平均分配的剩余空间时,元素的宽度等于内容大小 如果设置了width并且这个width的大小小于平均分配的剩余空间大小时,取平均分配的剩余空间

# VUE中input的focus事件如何阻止冒泡

image.png

image.png

image.png

image.png 直接加上就ok

父组件修改了 子组件用了v-if 的数据 页面没有刷新

父组件修改了数据 子组件用 v-if 页面没有变化

image.png

在子组件使用

 this.$set(this.newList[index], 'edit', true);
      this.$forceUpdate();

主要是 this.$forceUpdate();

保留两位小数

<el-input-number
          v-if="item.edit"
          :disabled="disabled"
          class="num"
          v-model="num"
          size="small"
          :controls="false"
          :min="0"
          :max="100000000"
          :precision="2"
        ></el-input-number>

整数就是:precision="0"

tofixed 返回的是string

image.png

可以是0不能是undefined

滚动条会使得input数字+

   <el-input
                    style="width: 200px"
                    @mousewheel.native.prevent
                    @DOMMouseScroll.native.prevent
                    min="0"
                    @keydown.native="channelInputLimit"
                    type="number"
                    :disabled="disabledStock || see"
                    clearable
                    :placeholder="
                      disabledStock ? '有规格提交时会自动汇总' : '请输入'
                    "
                    v-model="goodManageForm.stock"
                    @change="allStockHandle"
                  ></el-input>

自定义 el-form-item 校验

image.png

  <el-form-item
                 label-width="0"
                 :ref="'coupon' + relateIndex"
                 class="relevance_item relevance_coupon_item"
                 v-for="(relateStore,
                 relateIndex) in goodManageForm.productCoupons"
                 :key="relateIndex"
                 :prop="'productCoupons.' + relateIndex + '.quantity'"
                 :rules="goodManageRules.quantity"
               >
                 <div class="w-100 flex relevance_coupon">
                   <div class="tow duan">
                     <h4>{{ relateStore.couponName }}</h4>
                   </div>

                   <div class="three">
                     <el-input
                       :disabled="see"
                       min="0"
                       onkeyup="this.value=this.value.replace(/\D/g,'')"
                       @keydown.native="channelInputLimit"
                       class="elInput"
                       placeholder="请输入数量"
                       v-model="relateStore.quantity"
                       clearable
                       size="small"
                       type="number"
                       @change="couponQuantityBlur(relateIndex, $event)"
                     ></el-input>
                     <p style="width: 200px; margin-left: 16px">
                       剩余量:{{ relateStore.last }}
                     </p>
                   </div>
                   <span class="coupon_tips" v-show="relateStore.tips">{{
                     relateStore.tips
                   }}</span>

                   <div class="four">
                     <i
                       class="el-icon-delete icon_del"
                       @click="delectRelatedCoupon(relateStore)"
                     ></i>
                   </div>
                 </div>
               </el-form-item>

禁止输入负号

image.png

  channelInputLimit(e) {
      let keycode = e.keyCode;
      console.log('keyCode', keycode);
      let key = e.key;
      // 不允许输入'e'和'.'
      if (key === 'e' || key === '.' || keycode == 109 || keycode == 229) {
        e.returnValue = false;
        return false;
      }
      return true;
    },

父组件的值修改了 但是Dialog(子组件) 需要打开第二次才更新

image.png

先改成fasle再设置成true 我这里是在子组件设置了打开 www.jianshu.com/p/3595f26d5…

image.png

image.png

el-form-item 内部如果包含多个表单,默认校验失败时会将所有表单高亮

我的情况 image.png image.png

image.png 取消第一层的校验 加上required

image.png

image.png

image.png

因为我这个其实是一个数组

提示 :

vue.runtime.esm.js?2b0e:619 [Vue warn]: Invalid prop: type check failed for prop "value". Expected String, Number, got Array

想法一:多加一个数据判断这个数组是否为空 想法二:绑定的是数组的第一个值

image.png 想法二行不通 默认需要绑定定义的值

问题:el-form-item prop是数组 校验怎么处理?

学习:

//1.初始化的时候要设置为一个空的数组 editData : { headImageUrl: '', nickName: '', studentNumber: null, sex: null, dateOfBirth: '', ilicenseNo: '', nation: null, appointmentTime: null, politicsStatus: null, nativePlace: null, gradeClass: [] }; //2.自定义写rules //在method写好方法 //自定义验证 checkClass(rule, values, callback, data){ //自定义验证的逻辑 if(!this.editData.gradeClass || !this.editData.gradeClass.length ){ return callback(new Error(请选择年级班级)); }else{ return callback() } },


 

:rules直接写在标签上好找

学习:blog.csdn.net/snows_l/art… 多重数组 image.png

想法就是加一个能绑定数组的东西 然后再把它隐藏掉

总结:

其实数组绑定到 prop上也是没有问题的

image.png

本以为是缺少v-model 绑定的数据 我设置成了字符串结果还是 爆红

image.png

是因为这种Dialog不应该嵌套在el-form-item 里面写

el-table-column 禁用了还能打钩 vue+ele表格复选框禁用后点击行还能选中的问题解决(www.cnblogs.com/Ao-min/p/16…)

image.png

上面的处理是错误的这样点击行会把全部的选中都取消 应该是找到这一行 把这一行的打钩去掉

其实是在他打钩的瞬间去判断 符不符合打钩的规则

image.png

禁用多选框: www.cnblogs.com/cool-wan/p/…

image.png

把对象中 value 拿出来,拼接

 // item.quantity = null;
            item.specificationsStr = item.specifications
              .map(key => {
                return key.value;
              })
              .join(' , ');

input 有右侧上下箭头的样式 不用手写了

image.png

### el-input-number阻止外层的冒泡

image.png

image.png cloud.tencent.com/developer/a…

解决el-form-item 独占一行

image.png

element-ui form单独验证某个el-form-item

this.$refs.changeForm.validateField('newPhone')

多选框切换前需要做二次确认

image.png

使图片居中

用定位 ![image.png](p9-juejin.byteimg.com/tos-cn-i- k3u1fbpfcp/b020f47187164799841c19862d459df8~tplv-k3u1fbpfcp-watermark.image?)

如何让浏览器支持字体小于12px的解决办法

  • 解决方案:p{font-size: 12px; transform: scale(0.8);}

    1.chrome设置字体大小,当字体小于12px时候都以12px来显示,这时候可以用css3的 scale()缩放来解决
    
font-size:12px;
-webkit-transform:scale(0.84);

font-size:20px;
-webkit-transform:scale(0.5);


www.cnblogs.com/huahongyi/p…

兼容写法 有些浏览器允许设置小于 12px 的字体,那么你需要额外写一个类。

/* 优先采用 -webkit-transform 规则 */
.txt {
    -webkit-transform: scale(0.5)
}
 
/* 允许的浏览器采用以下规则 */
.fontSize {
    font-size:8px;
}

网上给出来的解决方案是用scale进行缩放,但这个操作没有cover到对文本的换行计算,导致文本每行文本的后面都有大部分留白。比较ok的解决方案是

.font-size-10px{
	font-size:20px;
	zoom:0.5;
}

需要注意,firefox不支持room属性,不过firefox对字体的大小是没有限制的,根据浏览器类型切换下样式就行

css 浏览器前缀

浏览器兼容问题五:CSS3兼容前缀表示

写法内核内核
-webkit-webkit渲染引擎chrome/safari
-moz-gecko渲染引擎Firefox
-ms-trident渲染引擎IE
-o-opeck渲染引擎Opera

image.png

vue element-ui实现table表格可编辑修改

el-ment ui

<template>
  <div class="st-table">
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="date" label="日期" width="180">
        <template slot-scope="scope">
          <input type="text" v-model="scope.row.date" v-show="scope.row.iseditor" />
          <span v-show="!scope.row.iseditor">{{scope.row.date}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="name" label="姓名" width="180">
        <template slot-scope="scope">
          <input type="text" v-model="scope.row.name" v-show="scope.row.iseditor" />
          <span v-show="!scope.row.iseditor">{{scope.row.name}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="address" label="地址">
        <template slot-scope="scope">
          <input type="text" v-model="scope.row.address" v-show="scope.row.iseditor" />
          <span v-show="!scope.row.iseditor">{{scope.row.address}}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button type="warning" @click="edit(scope.row, scope)">编辑</el-button>
          <el-button type="danger" @click="save(scope.row)">保存</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>
<script>
export default {
  data() {
    return {
      tableData: [
        {
          date: "2016-05-02",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1518 弄",
          iseditor: false
        },
        {
          date: "2016-05-04",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1517 弄",
          iseditor: false
        },
        {
          date: "2016-05-01",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1519 弄",
          iseditor: false
        },
        {
          date: "2016-05-03",
          name: "王小虎",
          address: "上海市普陀区金沙江路 1516 弄",
          iseditor: false
        }
      ]
    };
  },
  methods: {
    edit(row, index) {
      row.iseditor = true;
    },
    save(row, index) {
      row.iseditor = false;
    }
  }
};
</script>
<style lang="less" scoped>
.st-table {
  padding: 10px;
}
</style>

自定义的

image.png

右上角加数量提示

ui库有 Badge 标记

图片填充满父盒子

img { object-fit: cover; width: 100%; height: 100%; }

表单嵌套校验

image.png

image.png 改成flex布局

  <el-form-item
                        label-width="0"
                        :ref="'coupon' + relateIndex"
                        class="relevance_item relevance_coupon_item"
                        v-for="(relateStore,
                        relateIndex) in goodManageForm.productCoupons"
                        :key="relateIndex"
                        :prop="'productCoupons.' + relateIndex + '.quantity'"
                        :rules="goodManageRules.quantity"
                      >
                        <div class="w-100 flex relevance_item_son">
                          <div class="one"></div>
                          <div class="tow">
                            <div>{{ relateStore.couponName }}</div>
                          </div>

                          <div class="three">
                            <el-input
                              disabled
                              class="elInput"
                              placeholder="请输入数量"
                              v-model="relateStore.quantity"
                              clearable
                              size="small"
                              type="number"
                              @blur="couponQuantityBlur(relateIndex)"
                            ></el-input>
                          </div>
                          <div class="four">
                            <i
                              class="el-icon-delete icon_del not-click"
                              @click="delectRelatedCoupon(relateStore)"
                            ></i>
                          </div>
                        </div>
                      </el-form-item>

前端同一个项目 联调两个后端

image.png

方案:复制一份代码 再跑

Windows 7 系统屏幕切换

按住 win + p

金额数量太长

vue 数量太长 点点点不好看 image.png

image.png

.three-price {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 70px;
}

还可以用过滤器

 //文字数超出时,超出部分使用...
                ellipsis(value) {
                    if (!value) return ''
                    if (value.length > 10) {
                        return value.slice(0, 10) + '...'
                    }
                    return value
                }

方案二:文字过长用省略号显示且鼠标hover时展示完整内容

字体划线价

 划线价
      span:nth-of-type(2) {
        color: #a7a7a7;
        font-weight: 400;
        font-size: 12px;
        margin-left: 4px;
        text-decoration: line-through;
      }

没ui图真的不要写页面!!! image.png

需求 :图片需要在图片的下方

<div class="four_goods_classify">
          <img
            v-if="
              data.componentPropertyList[5] &&
                data.componentPropertyList[5].propertyName
            "
            class="image"
            :src="data.componentPropertyList[5].propertyName"
            alt=""
          />
</div>

css fixed布局

.four_goods_classify {
  position: relative;
  background-color: white;
  height: 48px;
  width: 100%;
  // line-height: 33px;
  .image {
    width: 100%;
    z-index: -1;
    height: 230px;
    overflow: hidden;
    // background-color: #f47900;
    img {
      width: 100%;
      top: 0;
      left: 0;
      position: fixed;
      z-index: -1;
    }
  }
}

使用函数绑定样式

:style="{'color':formateTitleColor(val)}"



//格式化标题颜色
			formateTitleColor(val){
				if(val<24 && val>=0){
					return '#f7b13f'
				}
				if(val>=24){
					
					return '#000'
				}
				if(val<0 ){
					return '#f5616f'
				}
				
			}

用scoped和非scoped样式 同时使用

想修改第三方组件的样式,又不想去掉scoped属性,影响别的组件。

<style>
/* 全局样式 */
/* 将修改第三方组件的样式写在这里 */
/* 组件的最外层标签定义一个唯一类,最好将样式都写在这个类名下,以防组件间互相影响 */
</style>
 
<style scoped>
/* 本地样式 */
</style>