1. 程式人生 > 其它 >vue2 - 元件中的通訊

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>