在組件傳值中,無論是props還是slot都是單向數據流,父組件向子組件傳值,子組件不能直接對父組件傳過來的值進行重新賦值。
下面學習子組件向父組件傳值的工具--emit。
在子組件emit設置傳遞的函數名和值
<template><view>子組件<button @click="$emit('add',Math.random())">提交</button></view>
</template>
子組件設置傳遞過去的函數名為add,值為一個隨機數
在父組件中接收:
通過@add="onAdd",其中add就是子組件的函數名
<template><view><xxm-child @add="onAdd"></xxm-child><view class="box" :style="{background:color}">{{num}}</view></view>
</template><script setup>import {ref} from "vue"const num = ref(0)const color = ref("#ccc")const onAdd =function onAdd(e){console.log(e)num.value=ecolor.value="#"+String(e).substring(3,6)}
</script><style lang="scss" scoped>.box{width: 100%;height: 50px;}
</style>
在父組件中,onAdd接收子組件傳遞過來的隨機數并轉化為字符串進行截取,得到一個顏色的隨機數。效果如下:
當點擊提交按鈕時,隨機數發生變化,顏色也隨之改變。
在實際開發中,emit通常需要在JS部分進行處理,上面的
@click="$emit('add',Math.random())"
在JS部分需要這樣寫
<template><view>子組件<button @click="onClick">提交</button></view>
</template><script setup>const emit = defineEmits(["add"])function onClick(){emit('add',Math.random())}
</script>
?可以實現一樣的效果。
如果子組件中涉及多個 ,可參照下面的方式進行處理:
子組件
<template><view>子組件<button @click="onClick">提交</button></view><view>------------</view><view><input type="text" @input="onInput" /></view>
</template><script setup>const emit = defineEmits(["add","change"])function onClick(){emit('add',Math.random())}function onInput(e){console.log(e.detail.value)emit("change",e.detail.value)}
</scipt>
父組件
<template><view><xxm-child @add="onAdd" @change="onChange"></xxm-child><view class="box" :style="{background:color,fontSize:size+'px'}">num:{{num}} </view></view>
</template><script setup>import {ref} from "vue"const num = ref(0)const size = ref(12)const color = ref("#ccc")const onAdd =function onAdd(e){console.log(e)num.value=ecolor.value="#"+String(e).substring(3,6)}function onChange(e){console.log(e)size.value=e}
</script>
?