vue之computed

computed的写法

在vue2x中,computed option语法有2种格式。一种是函数写法,一种是对戏那个写法

函数写法

computed: {
  fullName () {
    ...
  }
}

对象写法

computed: {
  fullName: {
    get: function () {
      ...
    },
    set: function () {
      ...
    }
  }
}

<b>小提示:</b>set方法只有在属性值发生边改时才会触发

computed的应用场景

总的来说,computed的诞生其实是为了解决频繁计算的问题。

比如说以前我们要计算单价和数量得到合计,会写一个method方法来计算,值发生改变的时候都会去执行这个方法,这样写固然没有问题,不过这样的写法不是最优雅的方案,因为它会频繁的执行,消耗性能,所以computed来了。

computed还有其他很多场景,但其实都是为了解决这样的问题,降低损耗,提升性能

computed的作用

  • computed计算属性依赖于其他属性和数据来计算值,只有数据发生改变,它才会执行,且只执行一次
  • computed解决了频繁计算的问题,提高了性能

小栗子

通过计算firstName和lastName得到fullName

 <h1>我是:{{ fullName }}</h1>
    <h1>我是:{{ fullNameSub }}</h1>
    <br />
    <button @click="onRename">通过set就可以修改属性的值</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      firstName: "张",
      lastName: "无忌",
    };
  },
  computed: {
    // getter写法
    fullName() {
      return this.firstName + this.lastName;
    },
    // setter写法
    fullNameSub: {
      get: function () {
        return this.firstName + this.lastName;
      },
      set: function (newValue) {
        console.log("newValue", newValue);
        console.log("值更新的时候会触发set");
      },
    },
  },
  methods: {
    onRename() {
      this.firstName = "赵";
    },
  },
};
</script>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容