vue 子页面调用父页面方法,如:修改页面保存成功后,刷新主页面列表

说明:使用事件将方法传递给子组件:可以在父页面中使用自定义事件来触发父页面的方法,并在子组件中监听该事件来执行相应的操作

父页面:

<template>  
  <div>  
    <child-component @custom-event="parentMethod"></child-component>  
  </div>  
</template>  
  
<script>  
import ChildComponent from './ChildComponent.vue';  
  
export default {  
  components: {  
    ChildComponent  
  },  
  methods: {  
    parentMethod() {  
      // 在这里定义父页面的方法逻辑  
    }  
  }  
}  
</script>

子组件(ChildComponent.vue):

<template>  
  <button @click="emitCustomEvent">触发自定义事件</button>  
</template>  
  
<script>  
export default {  
  methods: {  
    emitCustomEvent() {  
      this.$emit('custom-event'); // 触发自定义事件,将调用父页面的parentMethod方法  
    }  
  }  
}  
</script>
  • 9
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3 中,使用 `setup` 语法糖时,组件可以通过 `ref` 或 `reactive` 创建一个响应式对象,然后将组件的方法添加到该对象中,以便在组件中调用组件的方法。 以下是一个示例: ```javascript // 组件 ChildComponent.vue <template> <div> <button @click="childMethod">组件方法</button> </div> </template> <script> export default { methods: { childMethod() { // 组件的方法逻辑 } } }; </script> ``` ```javascript // 组件 ParentComponent.vue <template> <div> <ChildComponent :childMethod="childMethod" /> <button @click="callChildMethod">调用组件方法</button> </div> </template> <script> import { ref } from 'vue'; import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, setup() { const childMethod = ref(null); // 创建一个响应式对象 const callChildMethod = () => { if (childMethod.value) { childMethod.value(); // 在组件中调用组件的方法 } }; return { childMethod, callChildMethod }; } }; </script> ``` 在组件的 `setup` 函数中,我们创建了一个 `childMethod` 的响应式对象,并将其传递给组件。然后,我们在组件中定义了一个 `callChildMethod` 的方法,当点击组件中的按钮时,会调用组件中的方法。 注意:在组件中调用组件的方法时,需要判断 `childMethod.value` 是否存在,以避免在初始化阶段调用未定义的方法。 这样,当在组件中点击 "调用组件方法" 的按钮时,会触发组件中的 `childMethod` 方法

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值