vue3中defineEmits與defineProps的用法實例
vue3 setup語法糖中的defineEmits/defineProps的用法
這兩個 api 都是在 setup 語法糖里面使用的,并且不需要引入
defineProps:父組件給子組件傳遞參數(shù)
defineEmits:在子組件中調(diào)用父組件的回調(diào)函數(shù),并且可傳參
https://cn.vuejs.org/api/sfc-script-setup.html#defineprops-defineemits
defineEmits
父組件綁定在子組件中綁定自定義事件,子組件可用 emits 執(zhí)行
父組件綁定事件:
@increase="handleIncrease"父組件回調(diào)函數(shù):
const handleIncrease = (num: number) => {}子組件定義
emit:
// ts 專有
const emits= defineEmits<{
(e: 'increase', num: number): void
}>()
// js
let emits = defineEmits(['startChange', 'endChange'])
- 子組件調(diào)用
emit
emits('increase', 1);
父組件
<template>
<section class="parent">
<childVue :num="nums" @increase="handleIncrease"></childVue>
</section>
</template>
<script setup>
import childVue from './child.vue';
import { ref } from 'vue';
const nums = ref(0);
// 回調(diào)函數(shù)
const handleIncrease = (num: number) => {
nums.value += num;
};
</script>
子組件
<template>
<section class="box" @click="handelClick">{{ num }}</section>
</template>
<script setup>
// ts 專有
const emits= defineEmits<{
(e: 'increase', num: number): void
}>()
const handelClick = () => {
emits('increase', 1);
};
</script>
defineProps
父組件可直接向子組件傳值(只讀)
父組件
<template>
<div class="Father">
<p>我是父組件</p>
<!-- -->
<son :ftext="ftext"></son>
</div>
</template>
<script setup>
import {ref} from 'vue'
import Son from './son.vue'
const ftext = ref('我是父組件-text')
</script>
子組件
<template>
<div class="Son">
<p>我是子組件</p>
<!-- 展示來自父組件的值 在這里直接使用-->
<p>接收到的值:{{ftext}}</p>
</div>
</template>
<script setup>
import {ref} from 'vue'
// se
//defineProps 來接收組件的傳值
const props = defineProps<{
ftext: string,
}>()
// 復(fù)雜寫法
const props = defineProps<{
ftext: {
type: string,
required: false,
default: 'hhh'
}
}>()
// 在這里就用 props.sideCollapse
</script>
props 雙向綁定
當(dāng)我們想把父組件傳過來的參數(shù)變成雙向綁定時,即可讀也可寫
v-model:sideCollapse="sideCollapse"- 相當(dāng)于多綁定了一個自定義事件
update:sideCollapse emits('update:sideCollapse', 要變成的值)
父組件
<script setup lang="ts">
import { ref } from 'vue'
let sideCollapse = ref(false)
</script>
<template>
<nav-header v-model:sideCollapse="sideCollapse"></nav-header>
</template>
子組件
const props = defineProps<{
sideCollapse: boolean,
}>()
// let emits = defineEmits(['update:sideCollapse']) js寫法
// ts寫法
const emits = defineEmits<{
(e: 'update:sideCollapse', sideCollapse: boolean): void
}>()
function toggle() {
// props.sideCollapse = !props.sideCollapse 不能直接修改!
// 要這樣修改
emits('update:sideCollapse', !props.sideCollapse)
}
到此這篇關(guān)于vue3中defineEmits/defineProps的用法的文章就介紹到這了,更多相關(guān)defineEmits/defineProps的用法內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
vite創(chuàng)建vue3項目頁面引用public下js文件失敗解決辦法
Vue3相較于之前的版本有了不少變化,如引用全局Js文件,這篇文章主要給大家介紹了關(guān)于vite創(chuàng)建vue3項目頁面引用public下js文件失敗的解決辦法,文中通過代碼介紹的非常詳細,需要的朋友可以參考下2023-11-11
Vue項目中使用WebUploader實現(xiàn)文件上傳的方法
WebUploader是由 Baidu WebFE(FEX) 團隊開發(fā)的一個簡單的以 HTML5為主 , FLASH為輔 的現(xiàn)代 文件上傳組件 。這篇文章主要介紹了在Vue項目中使用WebUploader實現(xiàn)文件上傳,需要的朋友可以參考下2019-07-07

