一、父组件
<template>
<div>
<h2>我是父组件</h2>
<div>counter:{{ counter }}</div>
<button @click="callChildFun">调用子组件方法</button>
<children
:message="message"
@changeCounter="changeCounter"
ref="childrenRef"
></children>
</div>
</template>
<script>
import { ref } from "vue";
import children from "./children.vue";
export default {
components: {
children,
},
setup() {
const message = ref("hello");
const counter = ref(10);
//改变counter
function changeCounter(data) {
counter.value = data.value;
}
//这个常量名要和子组件的ref属性一致
const childrenRef = ref(null);
//父组件调用子组件的方法
const callChildFun = () => {
childrenRef.value.changeName("李四");
};
return {
message,
counter,
changeCounter,
childrenRef,
callChildFun,
};
},
};
</script>
二、子组件
<template>
<div>
<h2>我是子组件</h2>
<div>message:{{ message }}</div>
<div>name:{{ name }}</div>
<button @click="sendParent">发送数据</button>
</div>
</template>
<script>
import { ref } from "vue";
export default {
props: {
message: {
type: String,
default: "你好",
},
},
setup(props, context) {
console.log("message", props.message);
const counter = ref(20);
function sendParent() {
context.emit("changeCounter", counter);
}
const name = ref("张三");
//改变名字
function changeName(data) {
name.value = data;
}
return {
sendParent,
name,
changeName,
};
},
};
</script>
三、运行项目界面效果图如下
1.子组件message由你好变为hello
3.点击发送数据按钮 父组件counter由10变为20
四、总结
1.父组件给子组件传值有两种方式
(1)通过props传值
(2)在父组件中调用子组件方法传值
2.子组件给父组件传值 通过emit事件
出 处:https://www.cnblogs.com/xiao-wo-niu/
版权声明:本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文链接。
标签:const,name,counter,api,context,vue3,组件,message,ref From: https://www.cnblogs.com/xiao-wo-niu/p/16865037.html