vue中傳值:父?jìng)髯?子傳父

父組件向子組件傳值

子組件中的內(nèi)容

<template>
  <div class="itemWrap">
    <img :src="src" alt="">
    <!--<img src="../../static/img/1.png" alt="">-->
    <span>{{txt}}</span>
  </div>
</template>

<script>
  export default {
    name: "child",
    props:["src","txt"],
  }
</script>

<style scoped>
  .itemWrap{
    width: 25%;
    height: 100%;
  }
  .itemWrap img{
    width: 50%;
    height: 2rem;
    display: block;
    margin: 0.5rem auto 0 auto;
  }

</style>

父組件中的內(nèi)容

<template>
    <div class="tabbarWrap">
      <Item txt="首頁" src="../../static/img/1.png"></Item>
      <Item txt="購物車" src="../../static/img/2.png"></Item>
      <Item txt="收藏" src="../../static/img/3.png"></Item>
      <Item txt="逛逛" src="../../static/img/4.png"></Item>
    </div>
</template>

<script>
  import Item from './item'
    export default {
        name: "tabbar",
      components:{
        Item
      }
    }
</script>

<style scoped>
  *{margin: 0;padding: 0}
.tabbarWrap{
  width: 100%;
  height: 5rem;
  background: ghostwhite;
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  bottom: 0;
  left: 0;
}
</style>

重點(diǎn):
props的使用
與data一樣,props 可以用在模板中
可以在vm實(shí)例中像this.message這樣使用
與組件data函數(shù)return的數(shù)據(jù)區(qū)別
props的數(shù)據(jù)來自父級(jí)
data中數(shù)據(jù)是組件自己的數(shù)據(jù)

效果圖:


image.png

子組件向父組件傳值

子組件中的內(nèi)容

<template>
   <div>
     <!--點(diǎn)擊的時(shí)候向父組件傳值-->
     <h1 @click="fn">
       {{childmsg}}
     點(diǎn)擊我向父組件傳值
     </h1>
   </div>
</template>

<script>
   export default {
       name: "child",
     data:function () {
       return {
         childmsg:"子組件里面的信息",
         msg:"子組件里傳遞的值"
       }
     },
     methods:{
         fn:function () {
           //向子組件傳值
           this.$emit("change",this.msg)
         }
     }
   }
</script>

父組件中的內(nèi)容

<template>
 <div>
   <h1>父組件</h1>
   <h3>{{parentmsg}}</h3>
   <!--接受傳遞的值-->
   <child @change="getVal"></child>
   <input type="text" v-model="getmsg">
 </div>
</template>

<script>
 import Child from './child'

 export default {
   name: "father",
   data:function () {
     return{
       parentmsg:"父組件里面的信息!",
       getmsg:""
     }
   },
   components: {
     Child
   },
   methods:{
     getVal:function (val) {
       console.log(val)//拿到的值
       this.getmsg=val
     }
   }
 }
</script>

image.png

點(diǎn)擊子組件的文字后

image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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