组件之间传值

1、父组件传值给子组件

  父组件

<template>
  <div>
    父组件:
    <input type="text" v-model="name">
    <!-- 引入子组件 -->
    <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接受父组件的值,可以直接使用
    props: {
      inputName: String,
      required: true
    }
  }
</script>

 

 

2、子组件传值给父组件

  子组件

<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 v-on:childByValue="childByValue"></child>
  </div>
</template>
<script>
  import child from './child'
  export default {
    components: {
      child
    },
    data () {
      return {
        name: ''
      }
    },
    methods: {
      childByValue: function (childValue) {
        // childValue就是子组件传过来的值
        this.name = childValue
      }
    }
  }
</script>

 

3、非父子组件传值

  公共bus.js

import Vue from 'vue'
export default new Vue()

  

  或者不引入公共bus.js, 而是在main.js 中全局定义

Vue.prototype.bus = new Vue()

// 如果使用在main.js中引用,则在组件中的使用方法发生改变  由Bus 改为 this.bus
this.bus.$emit('', '')
this.bus.$on('',() => {
}
)

  组件1

<template>
  <div>
    A组件:
    <span>{{elementValue}}</span>
    <input type="button" value="点击触发" @click="elementByValue">
  </div>
</template>
<script>
  // 引入公共的bug,来做为中间传达的工具。若使用全局变量,则不需要引入
  import Bus from './bus.js'
  export default {
    data () {
      return {
        elementValue: 4
      }
    },
    methods: {
      elementByValue: function () {
        Bus.$emit('val', this.elementValue)
      }
    }
  }
</script>

  组件2

<template>
  <div>
    B组件:
    <input type="button" value="点击触发" @click="getData">
    <span>{{name}}</span>
  </div>
</template>
<script>
  import Bus from './bus.js'
  export default {
    data () {
      return {
        name: 0
      }
    },
    mounted: function () {
      var vm = this
      // 用$on事件来接收参数
      Bus.$on('val', (data) => {
        console.log(data)
        vm.name = data
      })
    },
    methods: {
      getData: function () {
        this.name++
      }
    }
  }
</script>

 

4、组件传值之前先解绑

beforeDestroy() {
    Bus.$off('val')
}


参考原文链接:https://blog.csdn.net/lander_xiong/article/details/79018737

posted @ 2019-01-24 14:43  爱学习的吴小瑞  阅读(315)  评论(0编辑  收藏  举报