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")
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值