Methods & Computed
methods基本使用
<template>
<div>
{{capacity}}
<br>
<button @click="increaseCapacity()">
++
</button>
</div>
</template>
<script>
...
setup(){
const capacity = ref(3)
function increaseCapacity(){
capacity.value++
}
return {
capacity,
increaseCapacity
}
}
...
</script>
- 在函数
increaseCapacity
中使用变量capacity
需要通过capacity.value
来访问(ref)包装对象capacity
的值 - 在
template
中访问变量{{capacity}}
会进行自动拆箱ref,暴露.value
- 注意:
- 虽然我们的methods可以写在setup中,但是因为是纯函数,我们可以用各种模块化的方法组织代码
- 虽然我们现在不可以使用this,但是我们可以当前作用域中可以访问的响应式的数据,防止因为this会导致的上下文的不可推断,this也对TS的支持非常差
- 我们需要思考代码拆分的方式,比如:一个状态+控制这个状态的逻辑放在一起
- 这里也要注意ref对象的拆装箱
计算属性 Computed
<template>
<div>
{{capacity}}
<br>
<p>
Spases Left: {{ sapcesLeft }} out of {{ capacity }} </p>
<li v-for="(name,index) in attending" :key="index">
{{name}}
</li>
<button @click="increaseCapacity()">
++
</button>
</div>
</template>
<script>
...
setup(){
const capacity = ref(3)
const attending = ref(["xx","xx","xx"])
function increaseCapacity(){
capacity.value++
}
const sapcesLeft = computed(() => {
return capacity.value - attending.value.length;
});
return {
capacity,
increaseCapacity,
attending,
sapcesLeft
}
}
...
</script>
- 注意:通过computed返回的值是一个readonly的ref,可读不可写,当然可以通过get/set方法进行读写操作