<script setup>
const say = () => console.log('hello')
</script>
<template>
<p @click="say">点我</p>
</template>
<style scoped></style>
<script>
export default {
setup() {
const say = () => console.log('hello')
return { say }
}
}
</script>
<template>
<p @click="say">点我</p>
</template>
<style scoped></style>
如图:上面的两图的效果是一致的。
使用 setup 有几件事必须做:默认导出配置选项,setup函数声明,返回模板需要数据与函数。
使用了语法糖后:写代码即可。
computed函数:定义计算属性
<script setup>
import { ref, computed } from "vue";
const scoreList = ref([80, 100, 90, 70, 60]);
// 计算属性
const betterList = computed(() => scoreList.value.filter((item) => item >= 90));
// 改变数据,计算属性改变
const fn = () => {
scoreList.value.push(92, 66);
}
</script>
<template>
<div>
<p>分数:{{ scoreList }}</p>
<p>优秀:{{ betterList }}</p>
<button @click="fn">添加</button>
</div>
</template>
点击前
点击后
总结:使用computed定义计算属性,当需要依赖的数据变化后,重新计算。
使用时,导入computed,使用后返回计算好的数据。