//子组件
<template>
<div class="hello">
<span>{
{ msg }}</span>
<div></div>
<span>{
{ num }}</span>
<button @click="add">+</button>
</div>
</template>
<script>
import {
ref, watch } from "vue";
export default {
name: "HelloWorld",
props: {
msg: {
type: String,
default: () => "默认值",
},
},
setup(props,context) {
// vue3.0 vue2.0
// context.attrs === this.$attrs
// context.slots === this.$slots
// context.emit === this.$emit
const num = ref(0);
const obj = ref("这是儿子的信息哦!")
watch(
() => props.msg,
(count, prevCount) => {
console.log(count);
console.log(prevCount);
}
);
function add() {
num.value += 1;
context.emit("sonMsg",obj.value);
}
return {
num,
add,
};
},
};
</script>
<style scoped lang="less">
</style>
//父级
<template>
<div id="home">
<div>{
{ msg }}</div>
<button @click="change">改变</button>
<input type="checkbox" />
<HelloWorld :msg = msg @sonMsg="farthMsg"></HelloWorld>
</div>
</template>
<script>
import {
ref, //ref() 函数用来根据给定的值创建一个(响应式的数据对象),传入的为基本数据类型,例如字符串、数字、boolean 等,返回值是一个对象,这个对象上只包含一个 value 属性
} from "vue";
import HelloWorld from "@/components/HelloWorld.vue";
export default {
name: "Home",
components:{
HelloWorld
},
setup() {
const msg = ref("这是父组件信息哦!");
function change(){
msg.value = "这是父亲的信息哦!";
}
function farthMsg(res){
console.log(res)
msg.value = res;
}
return {
msg,
change,
farthMsg
};
},
};
</script>
vue3.0——组件通信props、emit
猜你喜欢
转载自blog.csdn.net/weixin_49666910/article/details/114142612
今日推荐
周排行