文档看了很多遍, 依然是没搞清除这些是什么,就手动写了一个例子帮助自己理解:
home.vue
<template> <div class="home"> <img alt="vue logo" src="../assets/logo.png" /> <helloworld msg="welcome to your vue.js app" proper="1" @custome="handler"> <template v-slot:one> {{ home }} - 子组件插槽的数据: </template> </helloworld> </div></template><script>import helloworld from "@/components/helloworld.vue";export default { name: "home", data() { return { home: "主页", }; }, components: { helloworld }, methods: { handler(args) { console.log("子组件传递的参数:", args); }, },};</script>
helloworld.vue
<template> <div class="hello"> <h1>{{ msg }}</h1> <span>这里是插槽内容:</span> <slot slotone="01" name="one"></slot> <slot slottwo="02" name="two"></slot> <hr /> <button @click="$emit('custome', '参数')">点击传递参数</button> </div></template><script>export default { name: "helloworld", props: { msg: string, }, setup(props, context) { console.log("props:", props); console.log("context:", context); const { attrs, slots, emit } = context; console.log("attrs:", attrs); console.log("slots:", slots); console.log("emit:", emit); },};</script>
控制台输出:
props: proxy {msg: "welcome to your vue.js app"}context: {expose: ƒ}attrs: proxy {proper: "1", __vinternal: 1, oncustome: ƒ}slots: proxy {_: 1, __vinternal: 1, one: ƒ}emit: (event, ...args) => instance.emit(event, ...args)
继续展开:
结合图里面圈起来的部分,我大概得出的结论
context上下文这里应该是指helloworld这个组件
attrs也就组件的是那个$attrs(不含props,但是包含函数方法)
slots是组件插槽,并且是有被“使用”的插槽,因为另外一个插槽two没有对应的模板渲染
emit感觉是组件的自定义事件到底是什么呢?但是,这里看控制台输出实际上也得不出什么内容。
想知道以上4条结论理解是否正确。
大致是对的。唯有第一点稍稍有点儿问题,context 不是这个组件的真正对象,只是在 setup 时带了其中一部分信息的玩意儿,执行 setup 时这个组件对象还没被创建出来呢。
不知道题主以前接没接触过 vue2 或者 vue3 的 options api 写法,要是直接上来就是 vue3 composition api 确实不太容易理解。
后面仨其实就是 options api 里的 this.$attrs、this.$slots、this.$emit,因为 setup 时还没有 this 呢,所以变成了这样写。
【相关推荐:vue.js视频教程】
以上就是实例说明vue3中setup参数attrs,slots,emit是什么?的详细内容。