搭建自己的个人网站,郴州百度seo,wordpress栏目指定二级域名,wordpress 文件发送邮件vue中子组件不能直接修改父组件传来的prop值#xff0c;Prop 是一种传递数据的机制#xff0c;父组件通过 Prop 向子组件传递数据#xff0c;子组件通过 Props 接收父组件传递过来的数据#xff0c;这些数据被封装成一个个解构体形式的对象#xff0c;不能直接进行修改。这…vue中子组件不能直接修改父组件传来的prop值Prop 是一种传递数据的机制父组件通过 Prop 向子组件传递数据子组件通过 Props 接收父组件传递过来的数据这些数据被封装成一个个解构体形式的对象不能直接进行修改。这样做的好处是保证了单向数据流即只有父组件能够更新 Prop然后数据会自动流向子组件从而避免了数据的混乱与不可预测性。
方法一
使用事件触发机制 在 Vue 中子组件可以通过 $emit() 方法来触发父组件中定义的事件。当父组件收到事件时它可以调用一个方法来更新它自己的状态传递给子组件一个新的 Prop。这种方式可以让子组件告诉父组件需要更新的数据而不是直接修改它。
!--父组件--
templatedivchlid :prop1msg change-msgchangeMsg/chlid/div
/template
script
import Child from ./Child.vue;
export default{components:{Child},data(){return{msg:Hello,Vue!}},methods:{changeMsg(newMsg){this.msgnewMsg;//更新父组件中的数据}}
}
/script
!--子组件Child.vue--
templatediv{{prop1}}button clickchangeMsgChange Message/botton/div
/template
script
export default{props:{prop1:String},methods:{changeMsg(){this.$emit(change-msg,Hello,world!)//触发事件并传递新值}}
}
/script 方法二
使用计算属性
计算属性本质上是一个函数它接收一个参数并且返回一个根据这个参数计算得到的值。这个值可以在组件的模板中使用。
!--父组件--
templatedivchlid :prop1msg/chlid/div
/template
script
import Child from ./Child.vue;
export default{components:{Child},data(){return{msg:Hello,Vue!}}
}
/script
!--子组件Child.vue--
templatediv{{modifiedProp}}button clickchangeMsgChange Message/botton/div
/template
script
import Child from ./Child.vue;
export default{props:{prop1:String}computed:{modifiedProp:{get(){return this.prop1},set(newVal){this.$emit(update:prop1,newVal)}}}methods:{changeMsg(){this.modifiedPropHello,world!;//使用计算属性更新Prop的值}}
}
/script