【vue】computed计算属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<h2>add:{{add()}}</h2>
<h2>add:{{add()}}</h2>
<h2>sum:{{sum}}</h2>
<h2>sum:{{sum}}</h2>
x<input type="text" v-model.number="data.x"><br>
y<input type="text" v-model.number="data.y">
</div>
<script type="module">
import { createApp, reactive, computed } from './vue.esm-browser.js'
createApp({
setup() {
const data = reactive({
x: 12,
y: 25
})
//无缓存,每次调用都会重新计算
let add = () => {
console.log("add")
return data.x + data.y
}
//有缓存,相同结果不需要重复计算
const sum = computed(() => {
console.log("sum")
return data.x + data.y
})
return {
data,
add,
sum
}
}
}).mount("#app")
</script>
</body>
</html>