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 并没有什么用。

  • 相关阅读:
    BAT脚本打印空行的使用方法
    Shell脚本关于屏幕输出的字符进行颜色控制的问题
    shell脚本中切换用户执行相应的命令或者shell脚本的方法
    Linux下执行的java命令重定向到文件中的方法
    解决Firefox浏览器每次打开都弹出导入向导的问题
    解决Ruby在IE11中报Unable to get browser (Selenium::WebDriver::Error::NoSuchWindowError)的错误
    6月28日 Django form组件 和 modelform组件
    6月27日 ajax
    6月25日 Django 分页 cookie、session
    6月26日 Django 中间件
  • 原文地址:https://www.cnblogs.com/sophiazhu/p/10400738.html
Copyright © 2011-2022 走看看