溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

vue3中setup參數(shù)attrs,slots,emit實例分析

發(fā)布時間:2022-08-09 11:22:07 來源:億速云 閱讀:993 作者:iii 欄目:編程語言

這篇文章主要介紹了vue3中setup參數(shù)attrs,slots,emit實例分析的相關(guān)知識,內(nèi)容詳細(xì)易懂,操作簡單快捷,具有一定借鑒價值,相信大家閱讀完這篇vue3中setup參數(shù)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 }} - 子組件插槽的數(shù)據(jù): </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("子組件傳遞的參數(shù):", args);
    },
  },
};
</script>

Helloworld.vue

<template>
  <div class="hello">
    <h2>{{ msg }}</h2>
    <span>這里是插槽內(nèi)容:</span>
    <slot slotone="01" name="one"></slot>
    <slot slottwo="02" name="two"></slot>
    <hr />

    <button @click="$emit('custome', '參數(shù)')">點擊傳遞參數(shù)</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)

繼續(xù)展開:
vue3中setup參數(shù)attrs,slots,emit實例分析
結(jié)合圖里面圈起來的部分,我大概得出的結(jié)論

  • context上下文這里應(yīng)該是指helloworld這個組件

  • attrs也就組件的是那個$attrs(不含props,但是包含函數(shù)方法)

  • slots是組件插槽,并且是有被“使用”的插槽,因為另外一個插槽"two"沒有對應(yīng)的模板渲染

  • emit感覺是組件的自定義事件到底是什么呢?但是,這里看控制臺輸出實際上也得不出什么內(nèi)容。

想知道以上4條結(jié)論理解是否正確。

大致是對的。唯有第一點稍稍有點兒問題,context 不是這個組件的真正對象,只是在 setup 時帶了其中一部分信息的玩意兒,執(zhí)行 setup 時這個組件對象還沒被創(chuàng)建出來呢。

不知道題主以前接沒接觸過 Vue2 或者 Vue3 的 Options API 寫法,要是直接上來就是 Vue3 Composition API 確實不太容易理解。

后面仨其實就是 Options API 里的 this.$attrs、this.$slotsthis.$emit,因為 setup 時還沒有 this 呢,所以變成了這樣寫。

關(guān)于“vue3中setup參數(shù)attrs,slots,emit實例分析”這篇文章的內(nèi)容就介紹到這里,感謝各位的閱讀!相信大家對“vue3中setup參數(shù)attrs,slots,emit實例分析”知識都有一定的了解,大家如果還想學(xué)習(xí)更多知識,歡迎關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI