A component option that is executed before the component is created, once the
props
are resolved, and serves as the entry point for composition API’s
作为入口函数,一旦组件props被解析,其中的配置数据在组件实例被创建之前就被执行。
所以setup()的两个参数中,第一个参数就是props
。
// MyBook.vue export default { props: { title: String }, setup(props) { console.log(props.title) const { title } = props // 解构会丢失响应式 } }
同样地,setup()的参数props和组件属性props都是响应式的,文档中强调了直接对props解构的话会使其丢失响应式。如果需要解构的话可以用 toRefs
和 toRef
函数。
// MyBook.vue import { toRefs } from 'vue' setup(props) { const { title } = toRefs(props) console.log(title.value) } import { toRef } from 'vue' setup(props) { const title = toRef(props, 'title') console.log(title.value) }
第二个参数是context
对象。context在setup()中暴露三个属性 attrs
、slots
和 emit
上面提及在setup函数中还没有创建Vue实例,是无法使用vm.$attrs
、vm.$slots
和vm.$emit
的,所以这三个属性充当了这样的作用,使用方法相同。
注意:
context.attrs
和vm.$attrts
包含的是在实例vm.props
中没有被声明识别的attribute(class和style除外)。所以setup()中参数props
中暴露的变量,就不会在context.attrs
中暴露。
context.slots
和vm.$slots
只能访问具名插槽,没有命名的插槽或者v-slot:default
的是没有暴露的。
context的attrs
和slots
是有状态的,当组件更新时也会实时更新,所以也不要解构。但与props
不同的是,它们不是响应式的,在setup()中的使用应保持只读的状态,如果要改变可以在onUpdated的周期函数中进行。
context.emit
和vm.$emit
可以触发实例上的监听事件。
<!-- father.vue --> <template> <Child :msg="msg" greeting="nihao" @say="print"> <template v-slot:content> <p>这是插槽内容</p> </template> </Child> </template> <script> import Child from './child' export default { components: { Child }, data() { return { msg: 'a msg' } }, methods: { print(val) { console.log(val) // 早上好 } } } </script> <!-- child.vue --> <template> <div> <span>{{ num }}, {{ msg }}</span> <slot name="content"></slot> </div> </template> <script> import { ref, toRef } from 'vue' export default { props: { msg: String } setup(props, context) { const msg = toRef(props, 'msg') console.log(msg.value) // 'a msg' console.log(context.attrs) // {greeting: 'nihao', onSay: f()} console.log(context.slots) // {content: f()} context.emit('say', '早上好') const num = ref(1) return { num, msg } } } </script>
If
setup
returns an object, the properties on the object can be accessed in the component’s template.
setup() return出去的对象,将会进入到template中,并且可以访问。也可以return渲染函数动态加载节点。
toRef
函数返回的是包裹着的对象,其中value
属性是它的值,在setup()里msg.value
这样调用。return会自动拆装,在template中直接调用即可。
以上是自己阅读文档时的心得,如若有误望提醒指正。