这篇文章主要介绍了vue3中setup参数attrs,slots,emit实例分析的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇vue3中setup参数attrs,slots,emit实例分析文章都会有所收获,下面我们一起来看看吧。
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">
<h2>{{ msg }}</h2>
<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
呢,所以变成了这样写。
关于“vue3中setup参数attrs,slots,emit实例分析”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“vue3中setup参数attrs,slots,emit实例分析”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。