The method of pass values between different components in Vue

Pass values ​​to the parent component subassembly

Subassembly to the traditional values ​​parent component

Sons pass values ​​between the non-component

Sons value between the non-pass components, need to define common instances public file bus.js, as an intermediate repository to traditional values, or fail to pass effect between routing component values.

Public bus.js

//bus.js
import Vue from 'vue'
export default new Vue()

Component A: child1.vue

<template>
    <div>
        A组件:
        <span>{{elementValue}}</span>
        <input type="button" value="点击触发" @click="elementByValue">
    </div>
</template>
<script>
    // 引入公共的bug,来做为中间传达的工具
    import Bus from '../bus/bus.js'
    export default {
        name: "child1",
        data () {
            return {
                elementValue: 4
            }
        },
        methods: {
            elementByValue: function () {
            //重点代码:A组件将值传给B组件
                Bus.$emit('val', this.elementValue)
            }
        }
    }
</script>

<style scoped>
</style>

Component B: child2.vue

<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事件来接收A组件传给B组件的参数
      Bus.$on('val', (data) => {
        console.log(data)
        vm.name = data
      })
    },
    methods: {
      getData: function () {
        this.name++
      }
    }
  }
</script>

Reference Links: https://blog.csdn.net/lander_xiong/article/details/79018737

Published 15 original articles · won praise 11 · views 1676

Guess you like

Origin blog.csdn.net/sinat_34241861/article/details/104286676