vue3中子組件向父組件暴露方法並傳值,同樣兼容老寫法
1、父組件
<template>
<div class="home">
<h1>父組件</h1>
<img alt="Vue logo" src="../assets/logo.png" />
<HelloWorld @changeMsg="changeMsg" :msg="msg" />
<h1>{{num}}</h1>
</div>
</template>
<script>
import { reactive, toRefs } from 'vue';
import HelloWorld from '@/components/HelloWorld';
export default {
setup() {
const state = reactive({
msg: '點擊修改父組件傳值',
num: 0
});
let changeMsg = x => {
state.num += x;
};
return {
...toRefs(state),
changeMsg
};
},
name: 'Home',
components: { HelloWorld }
};
</script>
<style scoped>
.home {
color: red;
border: 1px solid red;
}
</style>
2、子組件
<template>
<div class="hello">
<h1>子組件</h1>
<h1 class="pointer" @click="notifyParent">{{ msg }}</h1>
</div>
</template>
<script>
import { toRefs } from 'vue';
export default {
setup(props, context) {
console.log(context);
let notifyParent = () => {
context.emit('change-msg', 2);
};
return {
...toRefs(props),
notifyParent
};
},
name: 'HelloWorld',
props: {
msg: String
}
};
</script>
<style scoped>
.hello {
margin: 20px;
color: green;
border: 1px solid green;
}
.pointer{
cursor: pointer;
}
</style>
setup的第二個參數中包含了 attr emit slot
其中emit用於向父組件提交事件,需要注意的是vue3中的emit中的方法名不再支持駝峰寫法,但父組件依舊支持駝峰和“-”間隔的寫法,
emit其余用法和vue2相同
效果圖

