需求:根据性别,年龄展示,这个人是男是女,在上什么学。 用v-if和computed 对比 一下

先来一个 v-if或者v-if的 展示办法

<template>
  <div v-if="testData">
    <!-- v-if 或者 v-show的展示方法 -->
    <template v-if="testData.gender && 6 <= testData.age <= 12">
      这位{{testData.gender}}同学 在上 小学
    </template>

    <template v-else-if="testData.gender && 12 < testData.age <= 18">
      这位{{testData.gender}}同学 在上 中学
    </template>

    <template v-else-if="testData.gender && 18 < testData.age ">
      这位{{testData.gender}}同学 在上 大学
    </template>
  </div>
</template>
<style lang="scss" scope>

</style>

<script>
export default {
  name: "test",
  data() {
    return {
      testData:{
        gender:"男", //女
        age:6, // 6-12 小学;12-18 中学;18大学
      }
    };
  },
};
</script>

再来一个 computed 的 办法

<template>
  <div v-if="testData">
    <!-- computed 的 方法 -->
    {{testDataTextComputed}}    
  </div>
</template>
<style lang="scss" scope>

</style>

<script>
export default {
  name: "test",
  data() {
    return {
      testData:{
        gender:"男", //女
        age:6, // 6-12 小学;12-18 中学;18大学
      }
    };
  },
  computed: {
    testDataTextComputed(){
      let testData = this.testData;
      if(testData && testData.gender && testData.age){
      	//错误处理
        if(6 <= testData.age <= 12){
          return `这位${testData.gender}同学 在上 小学`
        }else if(12 < testData.age <= 18){
          return `这位${testData.gender}同学 在上 中学`
        }else if(18 < testData.age){
          return `这位${testData.gender}同学 在上 大学`
        }
      }
    }
  },
};
</script>

上述的例子 不复杂,所以体现的 并不很明显,你可以想象一下,如果判断条件在多2个呢

  1. view 视图层 尽量写和页面展示有关的东西,逻辑尽量写在 javascript里
  2. 上面例子,如果修改代码,我想computed里的方法 更容易 让人去更改,而且可以 做 js 逻辑优化
  3. 当然也不是 不用v-if,v-show,有时候v-if,v-show配合 computed 效果更好,有时候只是简单的 非正即错 的要展示内容,v-if,v-show肯定更好
Logo

前往低代码交流专区

更多推荐