美文网首页
vue子组件和祖父组件的通讯

vue子组件和祖父组件的通讯

作者: lvyweb | 来源:发表于2022-05-30 20:35 被阅读0次

    son是father的子组件,father是grandfather的子组件。

    1. 子组件向祖父组件传值

    1.1 son组件

    <son @click="clickson"/>
    <script >
    export default {
    methods: {
        clickson (args) {
            this.$emit('clickfather', args) //args要传的参数
        }
    }
    }
    </script>
    

    1.2 father组件

    <father >
        <son @clickson='clickfather' />
    <father>
    <script >
    export default {
    methods: {
        clickfather (args) {
            this.$emit('clickgrandfather', args) //args要传的参数
        }
    }
    }
    </script>
    

    1.3 grandfather组件

    <grandfather >
        <father @clickfather='clickgrandfather'/>
    <grandfather>
    <script >
    export default {
    methods: {
        clickgrandfather () {
            console.log(args)//args要传的参数
        }
    }
    }
    </script>
    

    2. 祖父组件向子组件传值

    1. 1 grandfather组件

    <template>
      <div class="grandfather">
        <father :msg1="msg1" />
      </div>
    </template>
    
    <script>f
    import father from './father'
    export default {
      components: {father},
      data () {
        return {
          msg1: '疫情是6月1号解封?'
        }
      }
    }
    </script>
    

    1.2 father组件

    <template>
      <div class="father">
        <son :msg1="msg1" />
      </div>
    </template>s
    
    <script>
    import son from './son'
    export default {
      props: ['msg1'],
      components: {son},
    }
    </script>
    

    1.3 son组件

    <template>
    <div class="son">
      <p>{{msg1}}</p>
    </div>
    </template>
    
    <script>
    export default {
      props: ['msg1']
    }
    </script>
    

    相关文章

      网友评论

          本文标题:vue子组件和祖父组件的通讯

          本文链接:https://www.haomeiwen.com/subject/pfghurtx.html