实例说明vue3中setup参数attrs,slots,emit是什么?

 1356

文档看了很多遍, 依然是没搞清除这些是什么,就手动写了一个例子帮助自己理解,实例说明vue3setup参数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">
    <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参数attrs,slots,emit是什么?


结合图里面圈起来的部分,我大概得出的结论

context上下文这里应该是指helloworld这个组件

attrs也就组件的是那个$attrs(不含props,但是包含函数方法)

slots是组件插槽,并且是有被“使用”的插槽,因为另外一个插槽"two"没有对应的模板渲染

emit感觉是组件的自定义事件到底是什么呢?但是,这里看控制台输出实际上也得不出什么内容。

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

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

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

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


TAG标签:
本文网址:https://www.zztuku.com/detail-12928.html
站长图库 - 实例说明vue3中setup参数attrs,slots,emit是什么?
申明:本文转载于《segmentfault》,如有侵犯,请 联系我们 删除。

评论(0)条

您还没有登录,请 登录 后发表评论!

提示:请勿发布广告垃圾评论,否则封号处理!!

    编辑推荐