> 文章列表 > vue3中的setup

vue3中的setup

vue3中的setup

setup

  • 前言
    • setup中的两种返回值
    • setup执行的时机
    • setup的参数
    • 注意点:

前言

setup是vue3中的一个全新的配置项,值为一个函数;

setup是所有CompositionAPI(组合API)的基础,组件中所用到的数据、方法等都需要在setup中进行配置

setup中的两种返回值

  • 返回一个对象,对象中的属性、方法,在模板中均可直接使用
<template><div>{{ sayHello() }}</div><div>{{ name }}</div>
</template><script>export default {name: "App",setup() {// 数据let name = "张三";let age = "18";// 方法function sayHello() {alert(`我叫${name},我${age}岁了,你好啊`);}// 第一种return,返回一个对象return {name,age,sayHello,};},
};
</script>
  • 在vue2的配置中可读取到vue3配置中的属性和方法;在vue3的配置中不能读取vue2配置中的属性和方法
<template><div>{{ name }}</div><!-- <div>{{ sayHello() }}</div> --><div>{{ test2() }}</div>
</template><script>
export default {name: "App",data() {return {sex: "男",};},methods:{sayHello() {alert('你好啊')}},setup() {// 数据let name = "张三";let age = "18";function test2() {console.log(this.sex,'sex');console.log(this.sayHello,'sayHello');}// 第一种return,返回一个对象return {name,age,test2};},
};
</script>
  • 如果vue2和vue3的配置有冲突,则vue3的setup优先
data() {return {sex:'男'}
},
setup() {const sex = ref('女')return {sex}
}

setup执行的时机

在beforeCreate之前执行一次,this是undefined

beforeCreate(){console.log('beforeCreate');
},
setup(){console.log('setup',this);
}

setup的参数

第1个参数:props是一个对象,包含父组件传递给子组件的所有数据;在子组件中使用props进行接收。
第2个参数:context,是一个对象。该属性是props中没有声明接收的所有的对象;如果你使用props去获取值,同时props中你声明了你要获取的值
则:获取的值是undefined

//父组件
<template><Child msg="你好啊" aa="111"></Child>
</template>
<script>
import { ref } from "vue";
import Child from "./Child.vue";
export default {components: { Child },name: "App",setup() {return {};}
};
</script>
//子组件<template><div>{{ msg }}</div>
</template>    
<script>
export default {props:['msg'], // 需要声明一下接受到了,否则会报警告setup(props,context){console.log(props,context,'父传子接收到了');}
}
</script>

注意点:

①、vue3支持向下兼容,vue2中的data、methods配置项在vue3中都能够使用,但是尽量不要将vue3中的配置项和vue2.x配置项混用;

②、vue2.x配置(data、methods、computed等)中可以访问setup中的属性、方法,但是在setup中不能访问vue2.x配置(data、methods、computed等);

③、如果vue2配置与vue3配置存在重名,则以谁在上面谁优先展示;

④、setup不能是一个async函数,因为返回值不再是return的对象,而是promise,模板看不到return对象中的属性;