• Vue组件之间的通信


    1,父组件向子组件传参

    • 在父组件中,找到需要传递的子组件,并把消息赋值
    <template>
    <div> I am a 'a' component
    <com-b :prop-data="0" msgfromfather="I am your father"></com-b>
    </div>
    
    </template>
    
    
    <script>
    import comB from './b'
    export default {
        components: {comB},
        props: ['propData']
    }
    </script>
    • 在子文件中使用props

    Prop 是你可以在组件上注册的一些自定义特性。当一个值传递给一个 prop 特性的时候,它就变成了那个组件实例的一个属性。

    <template>
    <div>
      <div>{{msg}}</div>
      <div>{{msgfromfather}}</div>
      <button v-on:click="onClickMe">click me </button>
      </div>
    </template>
    
    <script>
     export default{
     data: function(){
          return {
          msg: 'this is Part B!'
          }
      },
          props: [
      'msgfromfather'   //注册父组件传递的消息
      ],
      methods: {
          onClickMe:  function(){
          console.log(this.msgfromfather)//可以直接调用
          }
      }
     }
    </script>

    2,子组件向父组件传递消息

    方法一:利用自定义事件 on和emit

    在父组件中自定义函数v-on:child-tell-me="listenToMyBoy"

    在子组件中触发定义的事件this.$emit("child-tell-me", this.msg), msg就是子组件传递的信息

    在父组件实现之前定义的方法‘listenToMyBoy’

    //父组件
    <template>
    <div> I am a 'a' component
    <p>Child component b tells me: {{childWords}}</p>
    <com-b :prop-data="0" msgfromfather="I am your father" v-on:child-tell-me="listenToMyBoy"></com-b>
    </div>
    
    </template>
    
    
    <script>
    import comB from './b'
    export default {
        data: function(){
            return {
            'childWords': '' //要在页面使用子组件传递的信息,需要声明一个参数
            }
        },
        components: {comB},
        props: ['propData'],
        methods: {
            listenToMyBoy: function(msg){
                this.childWords = msg;//信息传递给声明的参数
            }
        }
    }
    </script>
    //子组件
    <template> <div> <div>{{msg}}</div> <div>{{msgfromfather}}</div> <button v-on:click="onClickMe">click me </button> </div> </template> <script> export default{ data: function(){ return { msg: 'this is Part B!' } }, props: [ 'msgfromfather' ], methods: { onClickMe: function(){ //console.log(this.msgfromfather) this.$emit("child-tell-me", this.msg) } } } </script>

    如果是跨多层父子组件通信的话,$emit 并没有什么用。

  • 相关阅读:
    兼容Linux和Windows下获取视频截图
    webSocket通信
    解决IE浏览器弹出下载框的问题
    jsp的九大内置对象和四大作用域(转)
    如何确定神经网络的层数和隐藏层神经元数量
    Mac 修改系统默认Java版本
    Weka的使用
    在Mac OS系统中安装oracle
    P & NP & NPC & NP-HARD
    Dynamic programming——自下而上 VS. 自上而下
  • 原文地址:https://www.cnblogs.com/sophiazhu/p/10400738.html
Copyright © 2020-2023  润新知