语法:
Setup(props,context){}
setup 函数会在 beforeCreate 之后、created 之前执行
注意:在 setup() 函数中无法访问到 this
参数:
1:props:是响应式的,当传入新的 prop 时,它将被更新(因为 props 是响应式的,你不能使用 ES6 解构,因为它会消除 prop 的响应性)
export default { props: { title: String }, setup(props) { console.log(props.title) } }需要销毁 prop (可以通过使用 setup 函数中的 toRefs 来安全地完成此操作)
import { toRefs } from 'vue' setup(props) { const { title } = toRefs(props) console.log(title.value) }2:context(是一个普通的 JavaScript 对象,它暴露三个组件 property,它不是响应式,可以对它进行解构)
export default { setup(props, context) { // Attribute (响应式 object) console.log(context.attrs) // Slots (响应式 object) console.log(context.slots) // Emit 事件 (方法) console.log(context.emit) } }解构写法
export default { setup(props, { attrs, slots, emit }) { ... } }attrs 和 slots 是有状态的对象,在组件本身更新时总是更新它们。这意味着你应该避免对它们进行解构,并始终将属性引用为 attrs.x 或 slots.x。
如果你打算根据 attrs 或 slots 更改应用副作用,那么应该在 onUpdated 生命周期钩子中执行此操作。
创建vue3.0
npm i -g @vue/clivue create mydemo接下来按回车,安装列子1
reactive()函数接收一个普通对象,返回一个响应式的数据对象。
<template> <div class="hello"> <div>{{ readersNumber }} {{ book.title }}</div> </div> </template> <script> import { ref, reactive } from "vue"; export default { name: "HelloWorld", setup() { const readersNumber = ref(1); const book = reactive({ title: "Vue 3" }); // expose to template return { readersNumber, book, }; }, }; </script>注意,从 setup 返回的 refs 在模板中访问时是 Ref 展开,因此不应在模板中使用 .value
列子2
<template> <div class="hello"> </div> </template> <script> import { h, ref, reactive } from "vue"; export default { name: "HelloWorld", setup() { const readersNumber = ref(0); const book = reactive({ title: "Vue 3" }); // Please note that we need to explicitly expose ref value here return () => h("div", [readersNumber.value, book.title]); }, }; </script>在 setup() 内部,this 不会引用活动的实例,因为在解析其他组件选项之前调用了 setup(),因此 this 内部 setup() 的行为与其他选项中的 this 完全不同。
TIP:setup 是围绕 beforeCreate 和 created 生命周期钩子运行的,所以不需要显式地定义它们。
<template> <div class="hello"></div> </template> <script> import { onMounted, onBeforeMount } from "vue"; export default { name: "HelloWorld", setup() { onBeforeMount(() => { console.log("Component is onBeforeMount!"); }); // mounted onMounted(() => { console.log("Component is mounted!"); }); }, }; </script>
//HellowWorld.vue
<template> <div class="hello"> <MyMarker /> </div> </template> <script> import { provide, reactive, ref, readonly } from "vue"; import MyMarker from "./MyMarker.vue"; export default { components: { MyMarker, }, setup() { const location = ref("North Pole"); const geolocation = reactive({ longitude: 90, latitude: 135, }); provide("location", readonly(location)); provide("geolocation", readonly(geolocation)); }, }; </script>//MyMarker.vue
<template> <div> {{userLocation}}---{{userGeolocation.longitude}}---{{userGeolocation.latitude}} </div> </template> <script> import { inject } from "vue"; export default { setup() { const userLocation = inject("location"); const userGeolocation = inject("geolocation"); return { userLocation, userGeolocation }; }, }; </script>