1.父传子
父组件(传的值和传的方法)
引入组件无需注册
import Counter from "../../components/Counter.vue";
import { ref } from "vue";
传的值
const sex = ref('男')
传的方法
function FatherMethod(){
console.log('这是FatherMethod');
}
子组件(使用父组件传的值和调用父组件的方法)
我是子组件
import { ref,toRefs } from "vue";
调用父组件的方法
const emits = defineEmits(["FatherMethod"]);
const onAdd = () => {
emits("FatherMethod");
};
使用传过来的值
const props = defineProps(["sex"]);
or
const props = defineProps({
sex:String
});
const {sex} =toRefs(props)
2.子传父
父组件(使用子组件传的值和调用子组件的方法)
使用子组件的方法
//声明子组件
const Childs = ref(null);
const sonMethod = () => {
//子组件.value.方法
Childs.value.ChildMethod();
};
接收子组件传过来的值
我是父组件
子组件传递的值是 {{result}}
import Counter from "../../components/Counter.vue";
import {ref} from 'vue'
const result=ref('')
const sourceSon=(val)=>{
result.value=val.name
}
子组件(传的值和传的方法)
子组件传给父组件的方法
const ChildMethod = () => {
console.log('嗨害嗨,我是子组件');
};
//暴露出去
defineExpose({
ChildMethod
})
子组件给父组件传值
const emits1 = defineEmits(["toFather"]);
const toFather= () => {
let data={
name:'yy'
}
emits1("toFather",data);
};
精彩链接
发表评论