Vue組件傳值,父傳子,子傳父,非父子組件

1、父組件向子組件傳值
父組件paopao.vue

<template>
  <div class="app-container">
     <div id="paopao">
      <Alert v-if="alert" v-bind:message="alert"></Alert>
    </div>
  </div>
</template>

 <script>
  import Alert from './Alert'
  export default {
      name: 'paopao',
     data () {
         return {
             alert:'父組件向子組件傳遞的值'
         }
     },
     components:{
         Alert
     }
 }
 </script> 

2子組件Alert.vue

 <template>
    <div class="alert">
      {{message}}
    </div>
  </template>
  
  <script>
 export default {
   name: 'alert',
   props:['message'],
  data () {
     return {
       
     }
  }
 }
 </script>

3、子組件向父組件傳值
子組件child.vue
titleChanged是父組件中綁定的函數(shù)名

 <template>
      <div class="child">
          <input v-on:click="haha" type="button" value="子組件向父組件傳值">
      </div>
  </template>
  <script>
  export default{
      data(){
          return {
             val:"子組件的value值"
         }
     },
     methods:{
         haha(){
             this.$emit('titleChanged',this.val);
         }
     }
 }
 </script>

父組件father.vue

  <template>
      <div class="father">
          <h1>{{faval}}</h1>
          <child v-on:titleChanged="getValue"></child>
     </div>
  </template>
  <script>
  import child from './child.vue'
 export default{
     data(){
         return {
             faval:"Hello word!"         }
     },
     components:{
         child
     },
     methods:{
         getValue(data){
             this.faval = data
             console.log(this.faval)
         }
     }
 }
 </script>

非父子組件傳遞值
非父子組件之間傳值,需要定義工具文件eventHub.js進(jìn)行傳值,不然路由組件之間達(dá)不到傳值的效果
組件之間傳遞參數(shù)工具類eventHub.js

import Vue from 'vue'

export default new Vue()

組件A向組件B傳值
組件A.vue

 <template>
     <div class="classA">
         <input type="button" value="A組件向B組件發(fā)送值" v-on:click="returnHome">
      </div>
  </template>
  <script>
  import Hub from './eventHub.js'
  export default{
      data(){
         return {
             msg:4
         }
     },
     methods:{
         returnHome(){
             Hub.$emit('val',this.msg)
         }
    }
}
 </script>

組件B.vue

  <template>
      <div class="classB">
          <h3>{{name}}</h3>
      </div>
  </template>
  <script>
  import Hub from './eventHub.js'
  export default{
      data(){
         return {
             name:''
        }
     },
     mounted:function(){
         var that = this
         Hub.$on('val',(data)=>{
             that.name = data
         })
     }
 }
 </script>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容