登录  /  注册
首页 > web前端 > Vue.js > 正文

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

藏色散人
发布: 2022-08-09 10:59:26
转载
2086人浏览过

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

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(&#39;custome&#39;, &#39;参数&#39;)">点击传递参数</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.$attrsthis.$slotsthis.$emit,因为 setup 时还没有 this 呢,所以变成了这样写。

【相关推荐:vue.js视频教程

以上就是实例说明vue3中setup参数attrs,slots,emit是什么?的详细内容,更多请关注php中文网其它相关文章!

智能AI问答
PHP中文网智能助手能迅速回答你的编程问题,提供实时的代码和解决方案,帮助你解决各种难题。不仅如此,它还能提供编程资源和学习指导,帮助你快速提升编程技能。无论你是初学者还是专业人士,AI智能助手都能成为你的可靠助手,助力你在编程领域取得更大的成就。
来源:segmentfault网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
最新问题
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2024 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号