vue-setup函数,reactive,ref
setup函数,它将带有两个参数props(attrs),context(attrs,slots,emit),无权访问data,comuted,methods
在setup
中定义的变量或方法,都必须通过return {xxx,xxx}
暴露出去
在setup函数中,可以使用ref函数,用于创建一个响应式数据,当数据改变时,vue会进行响应
ref函数仅能监听基本函数类型的变化,不能监听复杂类型的变化,如数组和对象,本质是拷贝,与原始数据没有引用关系,简单的讲就是不会修改原始数据
import { ref } from 'vue'; function useChangeCount() { let count = ref(0); function change_count() { count.value += 1; } return { count, change_count } } export default useChangeCount; setup() { let { count, change_count } = useChangeCount(); return { count, change_count }; } <template> <div> <h1>{{ count }}</h1> <button @click="change_count">点我</button> </div> </template>
reactive的用法与ref的用法相似,也是将数据变成响应式数据,当数据发生变化时UI也会自动更新。不同的是ref用于基本数据类型,而reactive是用于复杂数据类型,比如对象和数组
<template> <div> <p>{{ user }}</p> <button @click="increase">click me! one year later</button> </div> </template> <script> import { reactive } from "vue"; export default { name: "reactive", setup() { const user = reactive({ name: "Alice", age: 12 }); function increase() { ++user.age } return { user, increase }; }, }; </script>
ref(user.name)
就相当于 ref('lemon')
也相当于 reactive({value:'lemon'})
reactive中传递的参数必须是json对象或者数组,如果传递了其他对象(比如new Date()),在默认情况下修改对象,界面不会自动更新,如果也需要具有响应式,可以通过重新赋值的方式实现
生命周期钩子、生命周期2x、生命周期3x
选项 API | Hook inside inside setup |
---|---|
beforeCreate |
Not needed* |
created |
Not needed* |
beforeMount |
onBeforeMount |
mounted |
onMounted |
beforeUpdate |
onBeforeUpdate |
updated |
onUpdated |
beforeUnmount |
onBeforeUnmount |
unmounted |
onUnmounted |
errorCaptured |
onErrorCaptured |
renderTracked |
onRenderTracked |
renderTriggered |
onRenderTriggered |
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> //Component is onBeforeMount! //Component is mounted!
interface Data { [key: string]: unknown } interface SetupContext { attrs: Data slots: Slots emit: (event: string, ...args: unknown[]) => void } function setup(props: Data, context: SetupContext): Data