vue3中$attrs的變化與inheritAttrs的使用( 二 )

vue2中 v-bind="$attrs" 和 $listeners//子組件.vue<template><div><el-button type="primary" @click="dialogVisible = true">點擊打開 </el-button><el-dialogv-bind="$attrs"v-on="$listeners" :visible.sync="dialogVisible"width="30%" :before-close="handleClose"><span>這是一段信息</span><span slot="footer" class="dialog-footer"><el-button @click="dialogVisible = false">取 消</el-button><el-button type="primary" @click="dialogVisible = false">確 定</el-button></span></el-dialog></div></template><script>export default {inheritAttrs: false, //不讓屬性直接渲染在根節點上data() {return {dialogVisible: false};},methods: {handleClose(done) {this.$confirm('確認關閉?').then(() => {done();}).catch(() => { });}}};</script>

vue3中$attrs的變化與inheritAttrs的使用

文章插圖
//父組件.vue<template><div><LianCom title="父組件給的標題" @open="openHandler"></LianCom></div></template><script>import LianCom from "../components/LianCom.vue"export default {components: {LianCom},methods:{openHandler() {console.log('可以直接注冊事件 , 因為 v-on="$listeners"會接收除了.native的原生事件')}}}</script>vue3v-bind="$attrs" 會接收屬性和事件//子組件<template><el-button text @click="dialogTableVisible = true"> 打開 </el-button><el-dialog width="600px" v-bind="$attrs" v-model="dialogTableVisible" title="我是標題"><div>我值彈窗中的內容</div></el-dialog></template><script lang="ts">export default {inheritAttrs: false,}</script><script lang="ts" setup>import {ref } from 'vue'const dialogTableVisible = ref(false)</script>ps:我們沒有向上拋出任何事件 。但是父組件可以調用 Element Plus 中對話框中的內置方法 。但是父頁面中可以 注冊 Element Plus 中對話框中的內置方法 。// 父組件<template><div class="father"><TestCom @close="closeHandler" :before-close="beforeclose" title="父組件給的標題" aa="我是aa" bb="我是bb"></TestCom></div></template><script setup lang="ts">import { ElMessageBox } from 'element-plus'import TestCom from "../../components/TestCom.vue"http:// Dialog 關閉的回調const closeHandler = () => {console.log('Dialog 關閉的回調')}/*before - close 只會在用戶點擊關閉按鈕或者對話框的遮罩區域時被調用 。如果你在 footer 具名插槽里添加了用于關閉 Dialog 的按鈕,那么可以在按鈕的點擊回調函數里加入 before - close 的相關邏輯 。關閉前的回調,會暫停 Dialog 的關閉. 回調函數內執行 done 參數方法的時候才是真正關閉對話框的時候.*/const beforeclose = (done: () => void) => {ElMessageBox.confirm('Are you sure to close this dialog?').then(() => {console.log('用戶點擊了確定')done()}).catch(() => {console.log('用戶點擊了取消')})}</script>
vue3中$attrs的變化與inheritAttrs的使用

文章插圖

推薦閱讀