Vue 3.x 计算属性

528 阅读1分钟

1、使用计算属性实现简单的字符串反转

<template>

  <h2>计算属性</h2>
  {{resersalMyStr}}
  <button @click="changeMyStr()">点击修改字符串</button>
  
</template>

<script>
export default {
  data() {
    return {
      reversalStr : '字符串反转实例'
    };
  },
  computed : {
    resersalMyStr(){
      return this.reversalStr.split('').reverse().join('');
    }
  },
  methods : {
    changeMyStr(){
      this.reversalStr = '我是修改过的字符串';
    },
  },
};
</script>

2、使用计算属性监听数据变化,实现两个字符串拼接

<template>

  <input type="text" v-model="firstName" placeholder="firstName">
  <input type="text" v-model="lastName" placeholder="lastName">
  {{splicingName}}
  
</template>

<script>
export default {
  data() {
    return {
      firstName: "",
      lastName: "",
    };
  },
  computed : {
    splicingName() {
      return this.firstName + " " + this.lastName
    }
  },
};
</script>

3、使用计算属性实现筛选功能

<template>

  <h2>计算属性实现筛选功能</h2>
  <input type="text" v-model="myKeywordColor" placeholder="请输入颜色">
  <ul>
    <li v-for="(item,index) in searchColorList" :key="index">{{item}}</li>
  </ul>
  
</template>

<script>
export default {
  data() {
    return {
      myKeywordColor : '',
      myListColor : ['red','white','green','gray','blue','black'],
    };
  },
  computed : {
    searchColorList() {
      var colorArr = [];
      this.myListColor.forEach((value) => {
        if (value.indexOf(this.myKeywordColor) != -1 && this.myKeywordColor != "") {
          colorArr.push(value)
        }
      })
      return colorArr;
    }
  },
};
</script>

4、(补充)使用watch监听数据变化,实现两个字符串拼接

<template>

  <input type="text" v-model="firstName" placeholder="firstName">
  <input type="text" v-model="lastName" placeholder="lastName">
  {{splicingName}}
  
</template>

<script>
export default {
  data() {
    return {
      firstName: "",
      lastName: "",
      splicingName: "",
    };
  },
  watch: {  //watch里不能写箭头函数
    firstName: function (value) {
      this.splicingName = value + " " + this.lastName;
    },
    lastName: function (value) {
      this.splicingName = this.firstName + " " + value;
    }
  }
};
</script>