组件中所有用到的:数据、方法等等,均可配置在setup中
setup有两种写法\
- 当函数来写
- 这个函数内部的变量/函数是局部的
- 这个函数的返回值 可以被当前组件的任意地方使用
- 这个函数内部不要使用this来操作组件数据
- setup返回的对象中的数据和data中的数据同名了 setup优先级更高
- setup在组件mounted加载期间 只会运行一次
- setup不能是一个async函数,因为返回值不再是return的对象,而是Promise,模板看不到return对象中的属性
export default {
data(){
return {msg:"vue3666"}
},
methods: {
fn(){
this.msg="666666"
}
}
setup(){
let text="测试"
function fn1(){
text="测试change"
}
// 通过return导出数据
return {text,fn1}
}
}
- 用作scrpt标签的属性
- 不用导出,数据、方法、在模板中均可直接使用
- 直接写上面setup函数中所有内容
<script setup>
let text="测试"
let obj=reactive({name:"lay",age:10})
function fn1(){
text="测试change"
// ref需要使用调用valve改变实现响应式数据
text1.value="测试change666"
}
let fn2=()=>{
console.log(obj);
obj.age=7
obj.name="luhan"
}
</script>