父组件调用子组件里的方法

审核中 Vue3 未结 已结 置顶 精帖
删除 置顶 取消置顶 加精 取消加精
66 0
yswl
yswl VIP3 2023-02-08 22:59:30
悬赏:60金币 编辑此贴

父组件:

<template>
  <div>
    <Son ref="RefChilde"></Son>
    <div class="btn btn-primary my-2" @click="fnCallChild">
      点我调用Son组件里的方法
    </div>
  </div>
</template>

<script>
import { defineComponent, ref } from "vue";
import Son from "../components/Son.vue";

export default defineComponent({
  name: "father",
  components: { Son },
  setup() {
    const RefChilde = ref();     //RefChilde 要和Son组件上的class名相同
    const fnCallChild = () => {
      RefChilde.value.sonFn();      //sonFn是子组件里的方法
    };
    return { RefChilde, fnCallChild };
  },
});
</script>

子组件:

<template>
  <div>
    <h1>{{ conts }}</h1>
  </div>
</template>

<script>
import { defineComponent, ref } from "vue";
export default defineComponent({
  setup() {
    const conts = ref("我是子组件");
    const sonFn = () => {
      conts.value = "我被父组件里调用了子组件的方法修改了数据";
    };
    return { conts, sonFn };
  },
});
</script>

示例:

父组件:

<template>
 <HelloWorld ref="RefChilde"></HelloWorld>
 <div class="btn btn-primary my-2" @click="fnCallChild">
       点我调用Son组件里的方法
 </div>
</template>

<script >
import { ref } from "vue";
import HelloWorld from '../components/HelloWorld.vue'
export default{
  name: "HomeView",
  components: { HelloWorld },
  setup() {
    const RefChilde = ref(false);     //RefChilde 要和Son组件上的class名相同
    const fnCallChild = () => {
      RefChilde.value.sonFn();      //sonFn是子组件里的方法
    };
    return { 
  RefChilde, 
  fnCallChild 
 };
  },
}
</script>

子组件:

<template>
  <div>
      <h1>{{ conts }}</h1>   
    <el-dialog
      v-model="conts"
      title="Tips"
      width="30%"
    >
      <span>This is a message</span>
      <template #footer>
        <span>
          <el-button @click="dialogVisible = false">Cancel</el-button>
          <el-button type="primary" @click="dialogVisible = false">
            Confirm
          </el-button>
        </span>
      </template>
    </el-dialog>
    </div>
</template>

<script>
import { ref } from "vue";
export default{
name:'HelloWorld',
  setup() {
    const conts = ref(false);
    const sonFn = () => {
      conts.value = true;
    };
    return { 
conts, 
sonFn 
};
  },
}
</script>