API-computed 基本使用

前些章节讲了一些常用的 api 如 setup, ref, reactive, toRef ... 等, 并以一个 todoList 的小案例来体现在 vue3 中如何进行解耦逻辑, 以 setup 函数作为调度的这种后端编程思想. 其实我个人觉得没啥, 就比较符合大众的编程习惯而已啦. 本篇继续来介绍计算属性 computed 是如何在 api 中应用的.

computed 的简单使用

<!DOCTYPE html>
<html lang="en">

<head>
<title>computed</title>
<script src="https://unpkg.com/vue@3"></script>
</head>

<body>
<div id="root"></div>
<script>
// computed 计算属性
const app = Vue.createApp({
setup () {
const { ref, computed } = Vue
const count = ref(0)
const dealClick = () => {
count.value += 1
}

// 其实就是定义一个变量, 给它写上逻辑, 自动计算啦
const countAddFive = computed(() => {
return count.value + 5
})

return { count, countAddFive, dealClick }
},
template: `
<div>
<span @click="dealClick">{{count}}</span> -- {{countAddFive}}
</div>
`,
})

const vm = app.mount('#root')

</script>
</body>

</html>

对简单的 computed 的使用流程则是:

  • 从 vue 中引入 computed
  • 定义一个属性变量 = computed(( ) => { 逻辑 })
  • return 该属性变量即可在 template 中使用啦

更复杂的一些用法, 则是能在 computed 的函数中去传入对象的操作, 如设置 get 和 set 的方法.

<!DOCTYPE html>
<html lang="en">

<head>
<title>computed</title>
<script src="https://unpkg.com/vue@3"></script>
</head>

<body>
<div id="root"></div>
<script>
// computed 计算属性
const app = Vue.createApp({
setup () {
const { ref, computed } = Vue
const count = ref(0)
const dealClick = () => {
count.value += 1
}

// 传入一个对象, 编写 get 和 set 的方法
let countAddFive = computed({
get: () => {
return count.value + 5
},

set: () => {
count.value = 666
}
})

setTimeout(() => {
countAddFive.value = 111
}, 3000);

return { count, countAddFive, dealClick }
},
template: `
<div>
<span @click="dealClick">{{count}}</span> -- {{countAddFive}}
</div>
`,
})

const vm = app.mount('#root')

</script>
</body>

</html>

set 方法当值发生变化时候就会自动调用, 然后 get 方法则再进行处理啦. 总之在这个 computed 的使用, 在通过 api 的方式也是非常简单的, 这里就不在探索啦, 咱只要知道它的基本使用流程就行, 在实际应用中还是能用到的, 比如算根据单价和数量, 自动算营业额呀, 算打分呀这些场景, 用 computed 则会让 code 看起来非常清晰和优雅呢.

耐心和恒心, 总会获得回报的.