vue3中的useAttrs和props的區(qū)別解析
vue3中的useAttrs和props的區(qū)別
在vue3中, 提供了一個 useAttrs 的方法它接收到的參數(shù)一 prop中可以接收到的數(shù)據(jù)是基本一樣的如果我們想自已寫一個組件, 把 elementPlus 中的期中一個組件封裝一下??梢赃@樣做
1.新建一個 自定義組件 myBtnCom
<template> <div class="mybuttonwrapper"> <el-button :="$attrs">Success</el-button> </div> </template> <script setup> </script>
從上面的代碼中, 我們可以在代碼中直接使用 $attrs 來接收所有的屬性也可以使用 useAttrs 函數(shù)import { useAttrs } from “vue”;let $attrs = useAttrs();
父組件中
<template> <div class="home-wrapper">Home</div> <el-button type="success" color="hotpink" round @click="changeSuccess">{{suctext}}</el-button> <myBtnCom type="success" color="hotpink" round></myBtnCom> </template>
在myBtnCom 設(shè)置的屬性和 elementPlus中的button的屬性是一樣的, 傳到組件內(nèi)部 ,就可以封裝一個和 elementPlus 用法一樣的組件了注意: 我們可以使用 useAttrs 接收到組件中傳遞的屬性, 同樣我們也可以使用 defineProps來接收, 但是如果我們使用 defineProps 接收過的屬性, 會要useAttrs 中消失, 這個特性要注意一下
補(bǔ)充:vue props和attrs
vue3
props 要先聲明才能取值,attrs不用聲明直接使用($attrs 包含 class and style attribute)
props 不包含事件,attrs包含
props 支持 String 以外的類型,attrs只有 String 類型
props 沒有聲明的屬性,會在 attrs 里,若在 props 內(nèi)聲明了該屬性,那么 attrs 里就不會出現(xiàn)該屬性
vue2與vue3的不同
包含所有父作用域的綁定 (class 和 style 除外)
props 不包含事件,attrs也不包含,事件通過$listeners監(jiān)聽
補(bǔ)充:
vue2官方
$attrs:
包含了父作用域中不作為 prop 被識別 (且獲取) 的 attribute 綁定 (class 和 style 除外)。當(dāng)一個組件沒有聲明任何 prop 時,這里會包含所有父作用域的綁定 (class 和 style 除外),并且可以通過 v-bind="$attrs" 傳入內(nèi)部組件——在創(chuàng)建高級別的組件時非常有用。
$listeners
包含了父作用域中的 (不含 .native 修飾器的) v-on 事件監(jiān)聽器。它可以通過 v-on="$listeners" 傳入內(nèi)部組件——在創(chuàng)建更高層次的組件時非常有用。
vue3
$listeners 被移除或整合到 $attrs
$attrs 現(xiàn)在包含 class and style attribute
到此這篇關(guān)于vue3中的useAttrs和props的區(qū)別的文章就介紹到這了,更多相關(guān)vue3 useAttrs和props區(qū)別內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vue-cli開發(fā)環(huán)境實現(xiàn)跨域請求的方法
本篇文章主要介紹了vue-cli開發(fā)環(huán)境實現(xiàn)跨域請求的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2018-04-04vue-resource post數(shù)據(jù)時碰到Django csrf問題的解決
這篇文章主要介紹了vue-resource post數(shù)據(jù)時碰到Django csrf問題的解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03