vue3中setup参数attrs,slots,emit实例分析

发布时间:2022-08-09 11:22:07 作者:iii
来源:亿速云 阅读:955

这篇文章主要介绍了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)

继续展开:
vue3中setup参数attrs,slots,emit实例分析
结合图里面圈起来的部分,我大概得出的结论

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

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

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

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

关于“vue3中setup参数attrs,slots,emit实例分析”这篇文章的内容就介绍到这里,感谢各位的阅读!相信大家对“vue3中setup参数attrs,slots,emit实例分析”知识都有一定的了解,大家如果还想学习更多知识,欢迎关注亿速云行业资讯频道。

推荐阅读:
  1. vue3中如何使用setup、ref和reactive
  2. Vue3中emits与attrs的区别有哪些

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

vue3 setup attrs

上一篇:vue3中setup函数的参数props和context怎么配置

下一篇:github访问速度慢的问题如何解决

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》