vue的基礎學習(三)-vue組件之間傳值

vue組件之間傳值:

    (1)父傳子

         原理: 父組件:利用自定義屬性進行傳值

                     子組件利用props進行接收使用

        父組件

<template>
  <div class="home">
    <h1>父組件</h1>

   //傳遞給兒子
    <children :toson='toson'></children>

  </div>
</template>

<script>

//引入子組件
import children from '@/views/Children'

export default {
  name: 'home',
  components: {
    children
  },
  data(){
    return {
      toson:'給兒子的', //傳遞給兒子的數據
    }
  }
}
</script>

     子組件

<template>
  <div class="about">
    <h1>子組件</h1>
  </div>
</template>

<script>
export default {
//接收父親傳遞的數據
  //    props:['toson'],
  props: {
    toson: {
      type: String
    }
  }
};
</script>

 

    (2)子傳父

         原理:兒子:利用this.$emit('自定義事件',傳輸數據)

                   父親:利用@自定義事件名=‘函數’ 進行接收

        子組件

<template>
  <div class="about">
    <h1>子組件</h1>
     //點擊向父組件進行傳值
    <button @click="send">點擊傳遞</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      aa: "兒子給父親的",
    };
  },
  methods: {
    send() {
      this.$emit("getson", this.aa);
    }
  }
};
</script>

           父組件

<template>
  <div class="home">
    <h1>父親</h1>
    <children @getson='geta'></children>
  </div>
</template>

<script>
import children from '@/views/Children'
export default {
  name: 'home',
  components: {
    children,
  },
  data(){
    return {
      //定義接收的初始值
      formson:''
    }
  },
  methods:{
    geta(data){
     //接收來自兒子的數據
      this.formson = data
    }

  },
}
</script>

 

(3)非父子關係之間傳值 -(任意組件之間傳值)

     原理: 利用中間商bus,bus爲vue的實例對象,向vue的實例對象的原型上添加vue實例

              傳值: this.bus.$emit('自定義事件',傳值數值)

             接收值:this.bus.$on('自定義事件',(data) => {})

    1.main.js進行bus的創建

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

Vue.config.productionTip = false

const bus = new Vue(); //創建vue實例
Vue.prototype.bus = bus; //向vue的原型鏈進行添加

new Vue({
  router,
  render: h => h(App)
}).$mount('#app')

 2. 傳遞數據的組件

<template>
    <div>
        <h3>傳遞數據組件</h3>
        <button @click='sendtoBrother'>向兄弟傳值</button>
    </div>
</template>

<script>
    export default {
        data(){
            return {
                toBrother:'給你的禮物'
            }
        },
        methods:{
            sendtoBrother(){
                //進行傳遞值
                this.bus.$emit('toborther',this.toBrother)
            }
        }
    }
</script>

<style lang="scss" scoped>

</style>

3.接收的組件

<template>
  <div class="about">
    <h1>接收數據</h1>
  </div>
</template>

<script>
export default {
  data(){
      return {
       comeBrother:'' 
     }
  }
  created(){
    //進行接收數據
    this.bus.$on('toborther',(data)=>{
        //data兄弟傳來的數據
        this.comeBrother = data
    })
  }
};
</script>

 

發佈了55 篇原創文章 · 獲贊 12 · 訪問量 4249
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章