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

不念不忘少年蓝@ 2022-04-02 15:14 365阅读 0赞

前些天发现了一个巨牛的人工智能学习网站,通俗易懂,风趣幽默,忍不住分享一下给大家。点击跳转到教程。

我们都知道通过$ref可以获取到某个DOM,但是它也可以用来获取子组件的实例,调用子组件的方法

例:
子组件:

  1. <template>
  2. <div></div>
  3. </template>
  4. <script>
  5. export default {
  6. methods:{
  7. childMethod(flag) {
  8. console.log(flag)
  9. }
  10. },
  11. created(){
  12. }
  13. }
  14. </script>

父组件: 在子组件中加上ref即可通过this.$refs.ref.method调用

  1. <template>
  2. <div @click="parentMethod">
  3. <children ref="child1"></children>
  4. </div>
  5. </template>
  6. <script>
  7. import children from 'components/children/children.vue'
  8. export default {
  9. data(){
  10. return {
  11. flag: true
  12. }
  13. },
  14. components: {
  15. 'children': children
  16. },
  17. methods:{
  18. parentMethod() {
  19. console.log(this.$refs.child1) //返回的是一个vue对象,所以可以直接调用其方法
  20. this.$refs.child1.childMethod(this.flag);
  21. }
  22. }
  23. }
  24. </script>

例子,兄弟组件间传递DOM数据,调用函数
写一个兄弟组件之间传递数据,父组件调用方法的案例:
第一个子组件cartcont,发射数据

  1. this.$emit('cartadd', event.target);

父组件接收数据,并将数据,通过调用另一个子组件shopcart 的方法传递给另一个子组件shopcart

  1. <v-cartcont :food="food" @cartadd='_drop'></v-cartcont>
  2. <v-shopcart ref='shopcart'></v-shopcart>
  3. _drop(target){
  4. console.log('父组件接收数据')
  5. this.$refs.shopcart.drop(target);
  6. }

shopcart子组件的方法

  1. drop(el){
  2. console.log('调用另一个子组件的方法')
  3. console.log(el)
  4. }

-——————————

转自:https://blog.csdn.net/qq\_34664239/article/details/80386153

发表评论

表情:
评论列表 (有 0 条评论,365人围观)

还没有评论,来说两句吧...

相关阅读