vue中ref与$parent/$children⽗⼦组件通信例子

在 Vue.js 中,ref 主要用于在模板中直接访问 DOM 元素或子组件实例,而 $parent 和 $children 主要用于在组件内部访问父组件和子组件实例,但通常不推荐频繁使用 $parent 和 $children 进行组件通信,因为它们会使组件之间的依赖关系变得复杂且难以维护。

不过,为了回答您的问题,我会给出使用这些特性进行通信的例子。

使用 ref

假设我们有一个父组件和一个子组件,并且我们想在父组件中直接访问子组件的某个方法或数据。

子组件 (ChildComponent.vue)

vue

<template>

  <div>

    <button @click="sayHello">Hello from Child</button>

  </div>

</template>

<script>

export default {

  methods: {

    sayHello() {

      console.log('Hello from Child method!');

    }

  }

}

</script>

父组件 (ParentComponent.vue)

vue

<template>

  <div>

    <ChildComponent ref="childRef" />

    <button @click="callChildMethod">Call Child Method</button>

  </div>

</template>

<script>

import ChildComponent from './ChildComponent.vue';

export default {

  components: {

    ChildComponent

  },

  methods: {

    callChildMethod() {

      this.$refs.childRef.sayHello(); // 直接访问子组件的方法

    }

  }

}

</script>

 

使用 $parent 和 $children

虽然不推荐,但这里是一个简单的例子。

子组件 (ChildComponent.vue)

vue

<template>

  <div>

    <p>{{ message }}</p>

  </div>

</template>

<script>

export default {

  data() {

    return {

      message: 'Hello from Child'

    }

  },

  mounted() {

    console.log(this.$parent.parentMessage); // 访问父组件的数据

  }

}

</script>

父组件 (ParentComponent.vue)

vue

<template>

  <div>

    <p>{{ parentMessage }}</p>

    <ChildComponent />

    <button @click="showChildMessages">Show Child Messages</button>

  </div>

</template>

<script>

import ChildComponent from './ChildComponent.vue';

export default {

  components: {

    ChildComponent

  },

  data() {

    return {

      parentMessage: 'Hello from Parent'

    }

  },

  methods: {

    showChildMessages() {

      // 注意:这里我们假设只有一个子组件,如果有多个,需要遍历 this.$children

      console.log(this.$children[0].message); // 访问子组件的数据

    }

  }

}

</script>

注意事项

尽量避免使用 $parent 和 $children,因为它们会使组件之间的依赖关系变得复杂且难以维护。

更好的方式是使用 props 和 events 进行父子组件之间的通信,使用 Vuex 进行跨组件通信,或者使用 provide/inject 进行非父子组件之间的通信。

 

  • 14
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值