1.父传子
父组件(传的值和传的方法)
<template>
<view>
引入组件无需注册
<Counter :sex="sex @FatherMethod="FatherMethod"/>
</view>
</template>
<script setup>
import Counter from "../../components/Counter.vue";
import { ref } from "vue";
传的值
const sex = ref('男')
传的方法
function FatherMethod(){
console.log('这是FatherMethod');
}
</script>
子组件(使用父组件传的值和调用父组件的方法)
<template>
<view>
我是子组件
<view class="button" @tap="onAdd">ADD</view>
<view >我是父组件传过来的:{{sex }}</view>
</view>
</template>
<script setup>
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)
</script>
2.子传父
父组件(使用子组件传的值和调用子组件的方法)
使用子组件的方法
<template>
<view>
<div @click="sonMethod">子传父</div>
<Counter ref="Childs"/>
</view>
</template>
<script setup>
//声明子组件
const Childs = ref(null);
const sonMethod = () => {
//子组件.value.方法
Childs.value.ChildMethod();
};
</script>
接收子组件传过来的值
<template>
<div >
我是父组件
<!-- clickChild是子组件绑定的事件,click是父组件接受方式 -->
<Counter @toFather="sourceSon"></Child>
<p>子组件传递的值是 {{result}}</p>
</div>
</template>
<script setup>
import Counter from "../../components/Counter.vue";
import {ref} from 'vue'
const result=ref('')
const sourceSon=(val)=>{
result.value=val.name
}
</script>
子组件(传的值和传的方法)
子组件传给父组件的方法
const ChildMethod = () => {
console.log('嗨害嗨,我是子组件');
};
//暴露出去
defineExpose({
ChildMethod
})
子组件给父组件传值
<template>
<view>
<view @click="toFather">toFather</view>
</view>
</template>
<script setup>
const emits1 = defineEmits(["toFather"]);
const toFather= () => {
let data={
name:'yy'
}
emits1("toFather",data);
};
</script>