vue计算属性官网地址:https://cn.vuejs.org/v2/guide/computed.html
使用场景:处理复杂的数据,需要逻辑运算时,比如:反转字符串 message.split('').reverse().join('')
如何体现computed 缓存功能,通过Math.random()函数即可
<template> <div> <button @click="changeValue">更新Value</button> <button @click="getComputedValue">打印computedValue</button> </div> </template> <script> export default { data() { return { value: 1, } }, computed: { computedValue() { return this.value + '--' + Math.random() }, }, methods: { changeValue() { this.value++ }, getComputedValue() { // 1.点击第二个按钮,多次获取computedValue的值时,返回的值都是相同的,Math.random()不会重新获取。体现了computed的缓存特性。 // 2.只有当点击了第一个按钮,修改了computedValue依赖的响应式数据后,才会更新computedValue的缓存 console.log(this.computedValue) }, }, } </script>