頁面:vue
父組件 <myfeedback></myfeedback> 子組件 <news></news> this
myfeedback.vuespa
1 <template> 2 <div> 3 <news :newInfo="info"><news> 4 <div @click="infoChange">按鈕</div> 5 </div> 6 </template> 7 8 <script>
import news from 'xxxxx' 9 export default { 10 name: "myfeedback", 11 data() { 12 return { 13 info: { 14 data1: 115 } 16 } 17 },
18 methods: { 19 infoChange() { 20 this.info.data1++ 21 } 22 } 23 }; 24 </script>
news.vue.net
1 <template> 2 <div> 3 <div>{{dataOne}}將父組件數據賦值給子組件數據,數據僅在mounted中渲染,父組件數據改變子組件數據不改變,須要用watch監聽</div> 4 <div>{{newInfo.dataOne}}直接使用父組件傳遞的數據,父組件數據改變子組件改變</div> 5 </div> 6 </template> 7 8 <script> 9 export default { 10 name: "news", 11 props: { 12 newInfo: { 13 type: Object 14 } 15 }, 16 watch: { 17 newInfo: { 18 handler(newValue, oldValue){ 19 this.newInfo = newValue 20 }, 21 deep:true 22 } 23 }, 24 data() { 25 return { 26 dataOne: 0 27 } 28 }, 29 mounted() { 30 this.dataOne = this.newInfo.dataOne; 31 } 32 }; 33 </script>
ps:code
1. 父組件傳的值在子組件中數據僅展現,可直接使用父組件傳的值,不用在子組件data中從新定義值component
2. 子組件要修改父組件的傳值,則須要在子組件中定義一個值a,初始化賦值。父組件值修改,子組件用watch監聽,a的值會相應作出改變。blog
參考文章 https://blog.csdn.net/qq_39692513/article/details/80791458ip