vue3中setup函数参数context,以及attrs,slots,emit分别是什么?

文档看了很多遍, 依然是没搞清除这些是什么,就手动写了一个例子帮助自己理解:
home.vue

<template>

<div class="home">

<img alt="vue3中setup函数参数context,以及attrs,slots,emit分别是什么?" src="../assets/logo.jpg" />

<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)

继续展开:
vue3中setup函数参数context,以及attrs,slots,emit分别是什么?
结合图里面圈起来的部分,我大概得出的结论

  1. context上下文这里应该是指helloworld这个组件
  2. attrs也就组件的是那个$attrs(不含props,但是包含函数方法)
  3. slots是组件插槽,并且是有被“使用”的插槽,因为另外一个插槽"two"没有对应的模板渲染
  4. emit感觉是组件的自定义事件到底是什么呢?但是,这里看控制台输出实际上也得不出什么内容。

想知道以上4条结论理解是否正确。


回答:

大致是对的。唯有第一点稍稍有点儿问题,context 不是这个组件的真正对象,只是在 setup 时带了其中一部分信息的玩意儿,执行 setup 时这个组件对象还没被创建出来呢。

不知道题主以前接没接触过 Vue2 或者 Vue3 的 Options API 写法,要是直接上来就是 Vue3 Composition API 确实不太容易理解。

后面仨其实就是 Options API 里的 this.$attrsthis.$slotsthis.$emit,因为 setup 时还没有 this 呢,所以变成了这样写。

以上是 vue3中setup函数参数context,以及attrs,slots,emit分别是什么? 的全部内容, 来源链接: utcz.com/p/936075.html

回到顶部