vue组件间的传值

父组件向子组件进行传值

父组件

<template>
  <div>
    父组件:
    <input type="text" v-model="name">
    <br>
    <br>
    <!-- 引入子组件 -->
    <child :inputName="name"></child>
  </div>
</template>
<script>
  import child from './child'
  export default {
    components: {
      child
    },
    data () {
      return {
        name: ''
      }
    }
  }
</script>

子组件

<template>
  <div>
    子组件:
    <span>{{inputName}}</span>
  </div>
</template>
<script>
  export default {
    // 接受父组件的值
    props: {
      inputName: String,
      required: true
    }
    //或者
    //props: ['inputName']
  }
</script>

 

 

子组件向父组件传值

子组件

<template>
  <div>
    子组件:
    <span>{{childValue}}</span>
    <!-- 定义一个子组件传值的方法 -->
    <input type="button" value="点击触发" @click="childClick">
  </div>
</template>
<script>
  export default {
    data () {
      return {
        childValue: '我是子组件的数据'
      }
    },
    methods: {
      childClick () {
        // childByValue是在父组件on监听的方法
        // 第二个参数this.childValue是需要传的值
        this.$emit('childByValue', this.childValue)
      }
    }
  }
</script>

 

父组件

<template>
  <div>
    父组件:
    <span>{{name}}</span>
    <br>
    <br>
    <!-- 引入子组件 定义一个on的方法监听子组件的状态-->
    <child @childByValue="childByValue"></child>
  </div>
</template>
<script>
  import child from './child'
  export default {
    components: {
      child
    },
    data () {
      return {
        name: ''
      }
    },
    methods: {
      childByValue(childValue) {
        // childValue就是子组件传过来的值
        this.name = childValue
      }
    }
  }
</script>

 

兄弟组件传值

首先在main.js中创建一个空的示例,并且将自定义的$bus绑定到原型上

Vue.prototype.$bus = new Vue()

 

发出方

this.$bus.$emit('fromB', id)

 

接收方

mounted () {
  let that = this;
  that.$bus.$on('fromB', data => {
     // console.log("接收到的数据:"+data);
  })
},

 

posted @ 2021-02-04 10:00  全村最靓的程序猿  阅读(567)  评论(0编辑  收藏  举报