vue父子之间方法的调用

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

<template>
  <div></div>
</template>

<script>
  export default {
    methods:{
      childMethod(flag) {
        console.log(flag)
      }
    },
    created(){
    }
  }
</script>

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

<template>
  <div @click="parentMethod">
    <children ref="child1"></children>
  </div>
</template>

<script>
  import children from 'components/children/children.vue'
  export default {
     data(){
      return {
        flag: true
      }
    },
    components: {      
      'children': children
    },
    methods:{
      parentMethod() {
        console.log(this.$refs.child1) //返回的是一个vue对象,所以可以直接调用其方法
        this.$refs.child1.childMethod(this.flag); 
      }
    }
  }
</script>

用$emit向父组件触发一个事件,父组件监听这个事件就行了。

直接用this.$parent.xxxx这样直接调用父组件的方法。
Parent.vue

<template id="">
    <child @refreshList="onRefresList"></child>
</template>

<script>
    export default {
        data () {
            return {
                
            };
        },
        components: {
            Child
        },
        mounted() {},
        methods: {
            onRefresList () {
                
            }
        },
        computed: {},
        watch: {}
    };
</script>


Child.vue

this.$emit('refreshList');

猜你喜欢

转载自blog.csdn.net/Salunone/article/details/84568608