Props 接收參數子組件改變父組件傳參

<div class="con">
	<button type="button" @click="title=!title">父點擊</button>
	<child :title="title"></child>
</div>
new Vue({
			data:{
				title:true
			},
			components:{
				'child':{
					template:`<div>
					    這是局部子組件{{title}}
						<button @click='title=!title'>點擊</button>
					</div>`,
					data(){
						return{
							
						}
					},
					props:{
						title:{
							type:Boolean
						}
					},
					methods:{
						click(){
							
						}
					}
				}
			},
			mounted() {
				window.aa=this.aa
			},
			methods:{
				aa:function(){
					console.log(21)
				}
			}
		}).$mount(".con")

報錯:錯誤原因:我在子組件裏操作父組件傳過來的值時報的錯,父子組件單向數據流,子組件不允許修改父組件的值,但是數組對象可以

如果要修改可以通過$emit觸發父組件裏的方法去修改

解決方法:通過計算屬性來實時監聽他的變化

new Vue({
			data:{
				title:true
			},
			components:{
				'child':{
					template:`<div>
					    這是局部子組件{{text}}
						父傳子{{titleText}}
						<button @click='click'>點擊</button>
					</div>`,
					data(){
						return{
							text:this.title
						}
					},
					props:{
						title:{
							type:Boolean
						}
					},
					methods:{
						click(){
							console.log(this.title)
							this.text=!this.text
						}
					},
					mounted(){
						console.log(this.title)
					},
					computed:{
						titleText(){
							return this.title
						}
					}
				}
			},
			mounted() {
				window.aa=this.aa
			},
			methods:{
				aa:function(){
					console.log(21)
				}
			}
		}).$mount(".con")
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章