在业务逻辑中,经常会有父组件调用子组件方法的情况,vue2.0 和 vue3.0 的使用中有些不一样,在这里总结下。

vue2.0 中的使用方法

父组件:

<template>
  <div @click="fatherMethod">
    <child ref="child"></child>
  </div>
</template>
<script>
  import child from '~/components/dam/child.vue';
  export default {
    components: {
      child
    },
    methods: {
      fatherMethod() {this.$refs.child.childMethods();
      }
    }
  };
</script>

子组件

<template>
  <div>{{name}}</div>
</template>
<script>
  export default {
    data() {
      return {
        name: '测试'
      };
    },
    methods: {
      childMethods() {
        console.log(this.name);
      }
    }
  };
</script>

在父组件中, this.$refs.child 返回的是一个vue实例,可以直接调用这个实例的方法

vue3.0 中和 2.0 的使用是有差异的

子组件, 该子组件是使用ant-design-ui 做的一个对话框

<template>
  <a-modal v-model:visible="visible" :title="title" :width="width">
    <template #footer>
      <a-button key="back" @click="handleCancel">取消</a-button>
      <a-button key="submit" type="primary" @click="handleOk">确定</a-button>
    </template>
    <slot></slot>
  </a-modal>
</template>
<script setup>
    import {  ref } from 'vue';
    const props = defineProps({
      title: {type: String},
      width: {type: String , default: '500px'}
    })
    let visible = ref(false)
    const openModal = () => {
      visible.value = true
    }
    const handleCancel = () => {
      visible.value = false
    }
    const emit = defineEmits(['closeModal'])
    const handleOk = () => {
      visible.value = false
      emit('closeModal')
    }
    defineExpose ({
      openModal
    })
</script>

父组件 是在其他组件中调用该对话框

<template>
<vModal
    ref="lookModal"
    width="600px"
    title="查看"
  >
    <div>对话框内容</div>
  </vModal>
</template>
<script setup>
import vModal from '@/components/modal/index.vue'
import {ref,reactive,computed,toRaw, watch} from 'vue'
  const lookModal = ref()
  const LookModol = (row) => {
    lookModal.value.openModal()
  }
</script>

在父组件中调用 LookModol 就可以调用子组件的方法, 这里需要注意的是 使用 语法糖的写法时, 需要将子组件中需要父组件调用的方法 通过defineExpose 暴露出来

后面的文章,会接着介绍 项目其他相关内容, 欢迎点赞加关注

这里介绍下本人做的头像,壁纸小程序,欢迎大家体验,
热门头像|个性头像|高清头像|性感壁纸|美女壁纸|炫酷壁纸|省电壁纸|唯美壁纸

posted on 2022-11-18 17:05  不锈钢子  阅读(87)  评论(0编辑  收藏  举报