vue组件间传参

1、父组件向子组件传参

  父组件:

    <template>

      <div>

        <Nav  :title="msg" :obj="userInfo"  />

      </div>

    </template>

    msg: 'data中数据',

    userInfo: {name: 'aa', age: 18}

  子组件:

    字符串数据写法

      props: ['title', 'obj']

    对象写法

      props: {

        title: String,

        obj: {

          name: String,

          age: Number

        }

      }

      props: {

        title: {

          type: String,

          default: '标题'

        }

      }

2、子组件向父组件传参

  第一种

  子组件:  

    <template>

      <div>

        <button  @click="send">按钮<button>

      </div>

    </template>

    send( ){

      this.$emit("child", 'abc')

    } 

  父组件   

    <template>

      <div>

        <Btn @child="receive"  />

      </div>

    </template>

    receive(data){

      console.log(data)  // 'abc'

    }

  第二种  

  父组件   

    <template>

      <div>

        <Btn ref="btn"  />

      </div>

    </template>

    receive( ){

      this.$refs.btn.msg  // xxx

      this.$refs.btn.tap( )  // 2222

    }

    mounted( ){

      this.receive( )

    }

  子组件

    msg: 'xxx'

    tap( ){console.log(2222)}

3、子组件操作父组件中的方法  

  子组件:  

    <template>

      <div>

        <button  @click="send">按钮<button>

      </div>

    </template>

    props: ['fun']

    send( ){

      this.$emit("child", this.fun)

    } 

  父组件   

    <template>

      <div>

        <Btn @child="receive"  :fun="tap"/>

      </div>

    </template>

    receive(data){

      data( )  // 1111

    }

    tap( ){

      console.log(1111)

    }

  

原文地址:https://www.cnblogs.com/cuishuangshuang/p/13161108.html