zoukankan      html  css  js  c++  java
  • 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 并没有什么用。

  • 相关阅读:
    【转】全国各地做生意十年的心得,忍不住上来感慨一下,诚信才是根基!
    pbootcms常用标签
    wordpress常用标签
    表格
    dedecms忘记后台密码
    新手建站基础步骤
    zblog常用插件及操作步骤
    织梦建站如何添加视频文件
    #Centos7.4#Shell中判断语句if中-z至-d的意思
    #Centos7.4#Linux虚拟机KVM配置网卡【Requested operation is not valid: network 'br0' is not active】
  • 原文地址:https://www.cnblogs.com/sophiazhu/p/10400738.html
Copyright © 2011-2022 走看看