发现组合式风格也很有用,决定尽快学习一波,按照自己的理解写的,如果有出入可以一起讨论
组合式风格的大体写法
除了一些钩子函数,我觉得setup里其实返回的都是变量,大体写法如下
<setup>
//变量的写法
const a = ref(...)
//函数的写法
const A = ( ) =>{
...
reuturn..
}
return {
a,
A,
}
//调用的时候写a,A就可以了
</setup>
定义变量(data的setup写法):
setup中定义的变量都应该是响应式的,否则变量值改变不会引起更新
<script>
import {ref} from 'vue'
export default{
setup(){
const a = ref(0)
//变量值的调用需要写a.value
return{
a
}
}
}
</script>
定义函数(method的setup写法):
函数直接写在setup里,然后记得return,调用的时候写函数名就可以了
<template>
<div>
<button @click="add_a">
{{a}}
</button>
</div>
</template>
<script>
import {ref} from 'vue'
export default{
setup(){
const a = ref(0)
function add_a(){
a.value++;
}
return {
a,
add_a
}
}
}
</script>
<style scoped>
</style>
一个简单的栗子:
按按钮增加变量的值,注意这里因为变量b不是可响应式的,因此b的值定义之后不会再被追踪,再在页面上也不会被更新
<template>
<div>
<button @click="add_a">
{{a+'--------'+b}}
</button>
</div>
</template>
<script>
import {ref} from 'vue'
export default{
setup(){
const a = ref(0)
let b = 0
function add_a(){
a.value++;
b++;
}
return {
a,
b,
add_a
}
}
}
</script>
<style scoped>
</style>
<script setup>写法
为了避免重复性且无聊的return,可以用script setup的写法,这种写法不需要写setup函数,也不用return
<template>
<div>
<button @click="add_a">
{{a+'--------'+b}}
</button>
</div>
</template>
<script setup>
import {ref} from 'vue'
const a = ref(0)
let b = 0
function add_a(){
a.value++;
b++;
}
</script>
<style scoped>
</style>