setup

1、setup 是 Vue3 中新增的钩子,它是我们在编写组件时的一个入口API
2、setup执行是在创建实例之前就是beforeCreate执行,所以setup函数中的this还不是组件的实例,
而是undefined,setup是同步的。并且,我们只能同步使用setup函数,不能用async将其设为异步。
3、setup 函数接收两个参数 props 和 context, 语法为:setup(props,context){}

基本使用

<template>
  <input type="text" v-model="name" /><br />
  {{name}}
</template>
<script>
import { ref } from 'vue'
export default {
    setup(){
        let name = ref('hello world')
        return {
            name
        }
    }
}
</script>

props

props 里面包含父组件传递给子组件的所有数据。在子组件中使用 props 进行接收 props 是响应式的, 当传入新的 props 时,会及时被更新 由于是响应式的, 所以不可以使用 ES6 解构,解构会消除它的响应式

context

context 里面包含 attrs, slots, emit 等数据方法 attrs:获取组件上的属性 slots:获取 slot 插槽的节点 emit :emit 方法(子组件向父组件传递数据)

<script>
export default {
  setup(props, context) {
    //获取传递的属性
    console.log(props)

    // 透传 Attributes(非响应式的对象,等价于 $attrs)
    console.log(context.attrs)

    // 插槽(非响应式的对象,等价于 $slots)
    console.log(context.slots)

    // 触发事件(函数,等价于 $emit)
    console.log(context.emit)
  }
}
</script>
powered by GitbookEdit Time: 2024-06-06 18:25:41