vue2 - 组件中的通信

props属性:

作用是让父组件可以给子组件传递data中的数据

注意子组件不能修改props中的数据,只能访问

父组件

<template>
  <div id="App">
    <!--给组件传入参数-->
    <human :name="name" :bodyObj="bodyObj"></human>
  </div>
</template>

<script>
import human from "./components/human"

export default {
  name: 'App',
  data(){
    return {
      name: 'levi',
      bodyObj: {
        balance: 1000,
        food: 'sandwich'
      }
    }
  },
  components: {
    human
  }
}
</script>

子组件

<template>
  <div>
    <!--组件使用参数-->
    <h1>{{name}}</h1>
    <h2>{{bodyObj.balance}}</h2>
    <h3>{{bodyObj.food}}</h3>
  </div>
</template>

<script>
  export default {
    name: 'Human',
    //组件接受参数
    props: ['name','bodyObj']
  }
</script>

<style> </style>

 

全局事件总线:

可以实现任意组件中的数据共享

main.js 开启全局事件总线

 

开启全局事件总线 - Vue.prototype.$bus=this

绑定全局事件总线 - this.$bus.$on("setBalance",this.setBalance)

解绑全局事件总线 - this.$bus.$off("setBalance")

调用全局事件总线 - this.$bus.$emit("setBalance",args)

import Vue from 'vue'
import App from './App.vue'

Vue.config.productionTip = false

new Vue({
  render: h => h(App),
  //开启全局事件总线
  beforeCreate() {
    Vue.prototype.$bus=this
  }
}).$mount('#app')

human.vue

<template>
  <div>
    <button @click="person">human操作person中的数据</button>
  </div>
</template>

<script>
  export default {
    name: 'Human',
    data(){
      return {
        balance: 100,
        like: "candy"
      }
    },
    //1.首先定义操作方法
    methods: {
      setBalance(value){
        this.balance=value
      },
      setLike(value){
        this.like=value
      },

      //操作person中的数据
      person(){
        this.$bus.$emit("setUsername","mikasa")
        this.$bus.$emit("setPassword","qqw")
      }
    },
    //2.绑定事件,让别的组件可以访问这些方法,操作数据
    mounted() {
      this.$bus.$on("setBalance",this.setBalance)
      this.$bus.$on("setLike",this.setLike)
    },
    //3.解绑事件
    beforeDestroy() {
      this.$bus.$off("setBalance")
      this.$bus.$off("setLike")
    }
  }
</script>

<style> </style>

person.vue

<template>
  <div>
    <button @click="human">person操作human中的数据</button>
  </div>
</template>

<script>
  export default {
    name: 'Person',
    data(){
      return {
        username: 'levi',
        password: '123'
      }
    },
    //1.首先定义操作方法
    methods: {
      setUsername(value){
        this.username=value
      },
      setPassword(value){
        this.password=value
      },

      //操作数据
      human(){
        this.$bus.$emit("setBalance",200)
        this.$bus.$emit("setLike","hamburger")
      }
    },
    //2.绑定事件,让别的组件可以访问这些方法,操作数据
    mounted() {
      this.$bus.$on("setUsername",this.setUsername)
      this.$bus.$on("setPassword",this.setPassword)
    },
    //3.解绑事件
    beforeDestroy() {
      this.$bus.$off("setUsername",this.setUsername)
      this.$bus.$off("setPassword",this.setPassword)
    }
  }
</script>

<style> </style>

 

posted on 2022-05-21 16:15  每天积极向上  阅读(35)  评论(0编辑  收藏  举报

导航