這篇文章主要介紹“uniapp組件傳值的方法有哪些”的相關知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“uniapp組件傳值的方法有哪些”文章能幫助大家解決問題。
創建子組件comp.vue,然后在index.vue父頁面使用該組件:
<template> <view class="content"> <image class="logo" src="/static/logo.png"></image> <comp :name="name" @getMsg="openMsg"></comp> </view> </template> <script> import comp from '../../components/comp.vue' import phone from '../../components/phone.vue' import phoneItem from '../../components/phoneItem.vue' export default { components: { comp, }, data(){ name: 'parent', } } </script>
可以看到在上面的index頁面中有一個數據為name,我們下面使用props將父組件的name值傳給子組件comp.vue。首先在父組件中使用子組件的上面進行綁定傳參:
<comp :name="name" ></comp>
然后在子組件comp.vue中使用props接收父組件傳過來的值:
然后設置一個點擊事件打印拿到的name的值
<script> export default { // 接收父傳給子的參數 props:{ name: String }, methods: { sendMsg() { console.log(this.name) } } } </script>
打印的值:
在子組件中使用this.$emit對父組件進行傳值
在comp.vue中:
methods: { sendMsg() { //子傳父 this.$emit('getMsg', "我是子,"+this.name); } }
在index.vue中:
定義openMsg方法綁定給@getMsg
<comp :name="name" @getMsg="openMsg"></comp>
然后寫openMsg方法:打印傳過來的值
methods: {<!--{cke_protected}{C}%3C!%2D%2D%20%2D%2D%3E-->openMsg(msg) {<!--{cke_protected}{C}%3C!%2D%2D%20%2D%2D%3E-->console.log(msg)}}
結果如下:這樣子組件編寫的值傳到了父組件中打印了出來
父給子傳值還是使用props方法,只是傳對象的話寫法有些區別
在父組件中:
<phoneItem v-for="(item,index) in songList" :item="item" :key="index"/>
現需要將song中songList的值傳過去
<script> import phoneItem from '../../components/phoneItem.vue' export default { components: { phoneItem }, data() { return { title: 'Hello', name: 'parent', song: { img: 'http://gw.alicdn.com/bao/uploaded/i3/1917047079/O1CN01VlEDD522AEJzpw3A5_!!2-item_pic.png_360x10000.jpg', title: 'Apple/蘋果 iPhone 11 Pro', price: '8699.00', marketPrice: '¥8699.00', }, songList: [ { img: 'http://gw.alicdn.com/bao/uploaded/i3/1917047079/O1CN01VlEDD522AEJzpw3A5_!!2-item_pic.png_360x10000.jpg', title: 'Apple/蘋果 iPhone 11 Pro', price: '8699.00', marketPrice: '¥8699.00', }, { img: 'http://gw.alicdn.com/bao/uploaded/i3/1917047079/O1CN01VlEDD522AEJzpw3A5_!!2-item_pic.png_360x10000.jpg', title: 'Apple/蘋果 iPhone 11 Pro', price: '8699.00', marketPrice: '¥8699.00', }, { img: 'http://gw.alicdn.com/bao/uploaded/i3/1917047079/O1CN01VlEDD522AEJzpw3A5_!!2-item_pic.png_360x10000.jpg', title: 'Apple/蘋果 iPhone 11 Pro', price: '8699.00', marketPrice: '¥8699.00', }, ] } } } </script>
子組件中進行接收:
<template> <view class="phone"> <image :src="item.img" mode="widthFix"></image> <view > {{item.title}} </view> <view class=""> <view class="price"> ¥{{item.price}} </view> <view class="market-price"> {{item.marketPrice}} </view> </view> </view> </template> <script> export default { //父傳給子的參數 props: { item: { type: Object, default() { return {} } } } } </script>
運行結果:
這樣就能把對象的值傳過來并且渲染:
關于“uniapp組件傳值的方法有哪些”的內容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業相關的知識,可以關注億速云行業資訊頻道,小編每天都會為大家更新不同的知識點。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。