1、先建立一個父組件 parent.vue,定義一個變量和一個數組,把它傳遞給子組件,代碼如下:
<template> <view> <testchild :title="title" :array="array" ></testchild> </view> </template> <script> import testchild from '../../components/testchild.vue' export default{ data(){ return{ title:"123", array:[ {id:"1",name:"xiaoming"}, {id:"2",name:"xiaoming1"}, {id:"3",name:"xiaoming2"}, ] } }, onLoad() { }, components:{ testchild, }, methods:{ } } </script> <style> </style>
2、新建testchild子組件,接收父組件的值和數組,代碼如下:
<template> <view > <text>父組件的值:{{title}}</text> <view>從父組件獲取到得數據:</view> <view v-for="item in array" :key="item.id"> <text>{{item.name}}</text> </view> </view> </template> <script> export default{ data(){ return{ } }, onLoad() { }, props:['title','array'], } </script> <style> </style>
3、如圖所示,子組件獲取到了父組件的數據:
4、父組件獲取子組件的數據,子組件代碼如下:
<template> <view > <button type="default" @click="parentValue">給父組件傳值</button> </view> </template> <script> export default{ data(){ return{ name:'張三', } }, onLoad() { // console.log() }, methods:{ parentValue(){ this.$emit('myEven',this.name) } } } </script> <style> </style>
5、父組件的代碼如下:
<template> <view > <text>從子組件獲取到得數據:{{name}}</text>
<testchild @myEven="getchild" ></testchild> </view> </template> <script> import testchild from '../../components/testchild.vue' export default{ data(){ return{ name:'' } }, onLoad() { }, components:{ testchild, }, methods:{ //這里得參數按照子組件傳參的順序 getchild(name){ console.log(name); this.name = name; } } } </script> <style> </style>
6、如圖所示,父組件得到子組件的數據:
7、我們嘗試新建一個父組件parent,在這里引用兩個組件,實現這兩個組件之間的傳值,父組件代碼:
<template> <view > <test-a></test-a> <test-b></test-b> </view> </template> <script> import testA from '../../components/a.vue' import testB from '../../components/b.vue' export default{ data(){ return{ } }, onLoad() { }, components:{ 'test-a':testA, 'test-b':testB, }, methods:{ } } </script> <style> </style>
8、我們新建一個a.vue,代碼如下:
<template> <view class=""> <text>這是a組件</text> <button type="default" @click="updateValue">修改b組件的值</button> </view> </template> <script> export default { data(){ return{ } }, methods:{ updateValue(){ uni.$emit('updataVal',"李四") } } } </script> <style> </style>
9、新建一個b.vue,代碼如下:
<template> <view class=""> 這是b組件,值為{{value}} </view> </template> <script> export default { data(){ return{ value:'張三' } }, methods:{ }, created() { uni.$on('updataVal',data=>{ console.log(data); this.value = data; }) } } </script> <style> </style>
10、我們來點擊一下a組件,可以發現b組件的值被a組件改變了。這就是兩個子組件之間的傳值方式,條件(必須同時引入同個頁面)
11、如果組件之間沒有任何關系,可以定義全局組件bus來改變值,或者使用vuex同樣也能達到效果。