vue 计算属性用法例子

126 阅读1分钟

动态样式

实现表格内不同数据展示对应的颜色

// DOM元素
<el-table>
    <el-table-column label="执行结果" width="180" align="center">
        <template slot-scope="scope">
         <template slot-scope="scope">
          <div class="event">
            <i 
              :class="scope.row.flag ? 'el-icon-loading' : 'el-icon-location'"
              :style="iconColor(scope.row.flag)">
            </i>
            {{ scope.row.flag ? "移动中" : "停留" }}
          </div>
        </template>
      </el-table-column>
</el-table>

// 计算属性
 computed: {
    firstNum(val) {
      return val => {
        // 接收的val为1显示红色,反之蓝色
        if (val) {
          return { color: "red" };
        } else {
          return { color: "blue" };
        }
      };
    }
},

image.png

在表头中显示此时此刻的日期、星期

// DOM元素
<el-table>
    <el-table-column :label="getNowFormatDate" width="180" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.name }}</span>
        </template>
      </el-table-column>
  </el-table>
  
// 计算属性
computed: {
    // 获取年月日 星期几
    getNowFormatDate() {
      let date = new Date(),
        year = date.getFullYear(), //获取完整的年份(4位)
        month = date.getMonth() + 1, //获取当前月份(0-11,0代表1月)
        strDate = date.getDate(); // 获取当前日(1-31)
      if (month < 10) month = `0${month}`; // 如果月份是个位数,在前面补0
      if (strDate < 10) strDate = `0${strDate}`; // 如果日是个位数,在前面补0
      let week = "日一二三四五六".charAt(new Date().getDay());//获取星期几
      console.log(`${year}-${month}-${strDate} 星期${week}`);
      return `${year}-${month}-${strDate} 星期${week}`;
    }
},

image.png