Vue项目问题总结(二)

783 阅读4分钟

1.基于Vue + Element, 解决当table滚动条滑到最下面,切换分页滚动条不置顶的问题


// 在table中加上:key="tableKey", tableKey默认值为0

// 在触发分页方法中加上
this.tableKey += 1

2.vue粒子背景插件

npm install vue-particles --save-dev
// 使用,main.js引用后
<vue-particles id="particles-js" color="#dedede" />
#particles-js{
    width: 100%;
    height: calc(100% - 100px);
    position: absolute;   //设置absolute,其他DIV设置为relative,这样这个例子效果就作为背景
  }

3. 下拉框有值却不能选中问题

问题描述:在使用VUE+element开发时,编辑页面需要回显值,但下拉框选不上其他的参数值 解决办法:强制刷新,在下拉框change事件中调用

this.forceUpdate()已达到强制刷新

4.vue项目首次登录报错Redirected when going from "/login" to "/" via a navigation guard

解决方法:在router.js中加入下面这段代码

const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location, onResolve, onReject) {
  if (onResolve || onReject) return originalPush.call(this, location, onResolve, onReject)
  return originalPush.call(this, location).catch(err => err)
}

5. vue路由跳转到外链

{
        path: 'update-img',
        component: Layout,
        children: [
          {
            path: 'https://baidu.com', // 需要跳转的的链接
            meta: { title: '上传图片' }
          }
        ]
      },

6. Element table 记录多页勾选数据

步骤一: table添加 ref="table"
步骤二: table添加@selection-change="selectTable"@select="select"

<el-table
  ref="table"
  :key="tableKey"
  :data="tableData"
  border
  stripe
  style="width: 100%"
  :height="tableHeight"
  @selection-change="selectTable"
  @select="select"
>

步骤三: data中定义存储数据的对象 multipleSelection: {}
步骤四: selectTable事件中根据分页存储数据,this.searchData.Page.PageIndex是页码

// 列表选择
selectTable(row) {
  this.multipleSelection[this.searchData.Page.PageIndex] = row
}
步骤五: 根据记录的数据在列表中寻找相同的数据,回显勾选

check() {
  this.nextTick(() => {
if (this.multipleSelection[this.searchData.Page.PageIndex]) {
this.multipleSelection[this.searchData.Page.PageIndex].map(item => {
this.tableData.map(val => {
if (item.FId === val.FId) {
this.$refs.table.toggleRowSelection(val)
}
})
})
}
})
}
步骤六: 我这里是切换分页重新获取数据,所以在重新获取数据的时候调用check方法\
步骤七: this.multipleSelection中的数据就是所有勾选的数据

7.获取绝对值

var a = -1
Math.abs(a) // 1

8. 删除依赖包

rimraf node_modules

9. 字符传与数组之间的转换

// 字符传转数组
var a='1,2,3'
arr.split(',').map(Number) // [1,2,3]
// 数组转字符传
var arr = [1,2,3]
arr.toString() // "1,2,3"

10. 推荐一个很不错的vue后台管理项目模板

https://panjiachen.github.io/vue-element-admin/#/login?redirect=%2Fdashboard

11. 推荐一个转换md样式的工具,且可以下载成html,作为简历也是很不错的选项

http://md.aclickall.com/

12. Element table 两列公用一个表头,以及合并相同列

<el-table
      :data="tableData"
      border
      stripe
      :header-cell-style="setColSpan"
      style="width: 100%;max-height: 300px"
      class="ados-table"
    >
      <el-table-column label="排序" align="center" min-width="100" prop="BrandSort">
        <template slot-scope="scope">
          <el-input v-model="scope.row.BrandSort" class="sortInput" />
        </template>
      </el-table-column>
      <el-table-column label="代码" align="center" min-width="100" prop="CustomerName">
        <el-table-column label="" align="center" min-width="100" prop="CustomerName1" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.CustomerName" />
          </template>
        </el-table-column>
        <el-table-column label="" align="center" min-width="100" prop="CustomerName1" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.CustomerName" />
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="部位" min-width="140" align="center" prop="SafeCompany">
        <template slot-scope="scope">
          <el-input v-model="scope.row.CustomerName" />
        </template>
      </el-table-column>
      <el-table-column label="钣金" align="center" min-width="100">
        <el-table-column label="拆装" align="center" min-width="100">
          <template slot-scope="scope">
            <el-input v-model="scope.row.CustomerName">
              <template slot="append"></template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="更换" align="center" min-width="100">
          <template slot-scope="scope">
            <el-input v-model="scope.row.CustomerName">
              <template slot="append"></template>
            </el-input>
          </template>
        </el-table-column>
      </el-table-column>
    </el-table>
    
    // 合并表头
    setColSpan({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0 && columnIndex === 1) {
        this.$nextTick(() => {
          if (document.getElementsByClassName(column.id).length !== 0) {
            document.getElementsByClassName(column.id)[0].setAttribute('rowSpan', 2)
            return false
          }
        })
      }
      if (rowIndex === 1 && (columnIndex === 0 || columnIndex === 1)) {
        return { display: 'none' }
      }
    }
    // 合并数据
    // 处理相同数据合并
    setTable() {
      const spanOneArr = []
      var concatOne = 0
      // 判断是否为最后一级
      this.tableData.forEach((item, index) => {
        if (index === 0) {
          spanOneArr.push(1)
        } else {
          if (item.OrderNumber === this.tableData[index - 1].OrderNumber) { // 需合并相同内容的判断条件
            spanOneArr[concatOne] += 1
            spanOneArr.push(0)
          } else {
            spanOneArr.push(1)
            concatOne = index
          }
        }
      })
      return {
        one: spanOneArr
      }
    },
    setTableNumber() {
      const spanOneArr = []
      var concatOne = 0
      // 判断是否为最后一级
      this.tableData.forEach((item, index) => {
        if (index === 0) {
          spanOneArr.push(1)
        } else {
          if (item.FrameNumber === this.tableData[index - 1].FrameNumber) { // 需合并相同内容的判断条件
            spanOneArr[concatOne] += 1
            spanOneArr.push(0)
          } else {
            spanOneArr.push(1)
            concatOne = index
          }
        }
      })
      return {
        one: spanOneArr
      }
    },
    // 合并行
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 1 || columnIndex === 10) {
        const _row = (this.setTable(this.tableData).one)[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
      if (columnIndex === 7 || columnIndex === 8 || columnIndex === 9) {
        // setTableNumber
        const _row = (this.setTableNumber(this.tableData).one)[rowIndex]
        const _col = _row > 0 ? 1 : 0
        return {
          rowspan: _row,
          colspan: _col
        }
      }
    }
   

效果如下:

微信截图_20210802170954.png

13.css文字渐变

backgroundlinear-gradient(to right, red, blue);
-webkit-background-clip: text;
color: transparent;

1.png

14.表格横向数据转为竖向,竖向数据转为横向现在是表格,前提是两组数据字段对应

// 竖向数据模板,返回1月所有数据,2月所有数据
const data = [
{
    NewCarSalesCount: 0,
    NewCarSalesMoney: 0,
    NewCarSingleMoney: 0,
    NewCarGrossProfit: 0,
    NewCarGrossMargin: 0,
    NewCarRebate: 0,
    NewCarRebateRate: 0,
    NewCarGrossProfitRebate: 0,
    NewCarGrossProfitRebateRate: 0,
    FinancialCount: 0,
    Permeability: 0,
    FinancialInCome: 0,
    FinancialSingleInCome: 0,
    FinancialGrossProfit: 0,
    InsuranceCount: 0,
    InsuranceRate: 0,
    InsuranceInCome: 0,
    InsuranceSingleMoney: 0,
    InsuranceGrossProfit: 0,
    InsuranceGrossProfitRate: 0,
    PartsInCome: 0,
    PartsSingleMoney: 0,
    PartsGrossProfit: 0,
    PartsGrossProfitRate: 0,
    LicenseCount: 0,
    LicensePermeability: 0
},
...
]
// 横向数据模板,显示为1到12月数据
var tableData = [
{ Plate: '整车', Project: '销量', YearCounts: '', parentId: 0, powerId: 1, showChild: false, key: 1, type: 0, m1: 0, m2: 0, m3: 0, m4: 0, m5: 0, m6: 0, m7: 0, m8: 0, m9: 0, m10: 0, m11: 0, m12: 0 },...
]
// 竖向数据转为横向
const keys = Object.keys(this.tableData[0])
const keys1 = Object.keys(data[0])
for (var i = 0; i < this.tableData.length; i++) {
   // 8 为对应的横向数据m1
   for (var j = 8; j < keys.length; j++) {
     this.tableData[i][keys[j]] = data[j - 8][keys1[i]]
   }
}
// 横向数据转竖向数据
const keys = Object.keys(arr[0])
const keys1 = Object.keys(this.paramsData[0])
for (var i = 0; i < this.paramsData.length; i++) {
  // 8 为对应的横向数据m1, 5为竖向数据多出的字段
  for (var j = 0; j < keys1.length - 5; j++) {
   this.paramsData[i][keys1[j]] = arr[j][keys[i + 8]]
  }
}

15. element 进度条超出100,如何正确显示文字,效果图如下

微信截图_20211118122822.png

// 代码 tableProgress: 设置最大值为100, progress:真正大于100 的值
<el-progress :percentage="scope.row.tableProgress" :stroke-width="20" :format="format(scope.row.progress)"></el-progress>
// 由于format接收的是function,所以方法里要这样写
format(percentage) {
      return () => {
        return percentage + '%'
      }
    }

16. 大屏数据自动滚动展示

// 下载插件
npm i vue-seamless-scroll --save
// 文件引入
import vueScroll from 'vue-seamless-scroll'
components: { vueScroll }
// 配置
computed: {
    classOption() {
      return {
        step: 0.2, // 数值越大速度滚动越快
        limitMoveNum: 2, // 开始无缝滚动的数据量 this.dataList.length
        hoverStop: true, // 是否开启鼠标悬停stop
        direction: 1, // 0向下 1向上 2向左 3向右
        openWatch: true, // 开启数据实时监控刷新dom
        singleHeight: 0, // 单步运动停止的高度(默认值0是无缝不停止的滚动) direction => 0/1
        singleWidth: 0, // 单步运动停止的宽度(默认值0是无缝不停止的滚动) direction => 2/3
        waitTime: 1000 // 单步运动停止的时间(默认值1000ms)
      }
    }
  }
 // 使用
 <vueScroll :data="stockData" :class-option="classOption" style="width: 100%;height: calc(100% - 16px);overflow: hidden;">
 <ul v-for="(item, index) in stockData" :key="index">
    <li class="CarSystem">{{ item.CarSystem }}</li>
  </ul>
 </vueScroll>
 // 运行看看

17. JS获取对象数组中的id的最大值或最小值

// 原数组
var arr = [{id: 3}, {id: 1}, {id: 2}]
// 期望数组中id最大值
Math.max(...arr.map(a => a.id))
// 期望数组中id最小值
Math.min(...arr.map(a => a.id))

18. 点击按钮实现复制功能

 // 点击事件如下
 handleOk() {
      let oInput = document.createElement('input');
      oInput.value = '我是被复制得内容跟'
      document.body.appendChild(oInput);
      oInput.select(); // 选择对象;
      document.execCommand("Copy"); // 执行浏览器复制命令
      oInput.remove()
      this.$message.success('复制成功')
    }

19. 管理系统主页面嵌套子页面效果

// 主页面点击新增,编辑或其他需要跳转页面的可使用此方法,只切换页面不改变路由,搭建页面如下
<keep-alive include="List,OnAdd">
  <component
   @onHandle="onHandle"
   @onGoBack="handleGoBack"
   :record="record"
   :typeView="type"
   :is="currentComponet"
   :ref="currentComponet"
   businessType="资产闲置"
></component>
    </keep-alive>
  // 其中
  //显示组件
  currentComponet: 'List',
  //页面跳转参数
  record: '',
  // 类型
  type: ''
 // 跳转事件
 onHandle(data) {
  this.record = data.record;
  this.currentComponet = data.handle;
  this.type = data.type;
 }
 // 返回事件
 handleGoBack(form) {
 this.record = ''
 this.currentComponet = from;
 }
 
 
 // 主页面中使用方法如下
 this.$emit('onHandle', { record: record, handle: 'list', type: 'view' });

19. 树形结构表格筛选,搜索最后一级满足条件的数据

// 树形结构如下
let arr = [
 {
  title: '1',
  children: [
    { 
      title: '2',
      children: [
        {
          title: '3',
          children: []
        }
      ]
    }
  ]
 },
 {
  title: '4',
  children: [
    {
      title: '33',
      children: []
    }
  ]
 }
]
// 筛选满足条件的数据,并保留上级结构,搜索最后一级满足条件的数据
const rebuildData=(value, arr) => {
  	let newarr = [];
  	arr.forEach(element => {
    if (element.children && element.children.length) {
      const ab = rebuildData(value,element.children);
      const obj = {
        ...element,
        children: ab
      };
      if (ab && ab.length) {
        newarr.push(obj);
      }
    } else {
      if (element.title.indexOf(value) > -1) {
        newarr.push(element);
      }
    }
  });
  return newarr;
};
rebuildData('2', arr)