主要作用:将分隔开得数据和方法,可以囊括在一起使用。
setup
setup:在创建组件之前,比beforeCreate还要前面
没用setup时的例子:
<template>
<div class="about">
<h1 @click="changeEvent">计数:{{count}}</h1>
</div>
</template>
<script>
export default{
name:'App',
data(){
return {
count:0
}
},
methods:{
changeEvent(){
this.count++
}
}
}
</script>
用了setup后的代码:
<template>
<div class="about">
<h1 @click="changeEvent">计数:{{count}}</h1>
<h1 @click="changeNum">计数:{{num}}</h1>
</div>
</template>
<script>
import { ref } from 'vue'
export default{
name:'App',
data(){
return {
count:0
}
},
methods:{
changeEvent(){
this.count++
}
},
setup(){
const num = ref(0)
function changeNum(){
//ref(0)这个值是保存在num里面
num.value+=5
}
return {num,changeNum}
}
}
</script>
reactive是个响应对象
<template>
<div class="about">
<h1 @click="changeEvent">计数:{{count}}</h1>
<h1 @click="changeNum">计数:{{num}}</h1>
<h1>用户名:{{user.username}}</h1>
<h1>用户名:{{user.type}}</h1>
</div>
</template>
<script>
import { ref,reactive } from 'vue'
export default{
name:'App',
data(){
return {
count:0
}
},
methods:{
changeEvent(){
this.count++
}
},
setup(){
const num = ref(0)
const user =reactive({
username:"Betty",
age:22,
type:"爱学习"
})
function changeNum(){
//ref(0)这个值是保存在num里面
num.value+=5
}
return {num,changeNum,user}
}
}
</script>
使用toRef将reactive解析成ref
<template>
<div class="about">
<h1 @click="changeEvent">计数:{{count}}</h1>
<h1 @click="changeNum">计数:{{num}}</h1>
<h1>用户名:{{username}}</h1>
<h1>用户名:{{type}}</h1>
</div>
</template>
<script>
import { ref,reactive,toRefs } from 'vue'
export default{
name:'App',
data(){
return {
count:0
}
},
methods:{
changeEvent(){
this.count++
}
},
setup(){
const num = ref(0)
const user =reactive({
username:"Betty",
age:22,
type:"爱学习"
})
function changeNum(){
//ref(0)这个值是保存在num里面
num.value+=5
}
return {num,changeNum,...toRefs(user)}
}
}
</script>