1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Vue父子组件传值问题

Vue父子组件传值问题

时间:2020-04-07 10:55:32

相关推荐

Vue父子组件传值问题

今天在编写vue子组件时遇到的两个问题来分享以下

父子组件传值问题

父组件

<md-editor ref="mdEditor" :text="form.content" height="400px"></md-editor>

子组件

<div><v-md-editor v-model="content":disabled-menus="[]"@upload-image="handleUploadImage"height="400px"></v-md-editor></div>

export default{props: {text: ""}}

然后就发生了以下问题

[Vue warn]: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-renders. Instead, use a data or computed property based on the prop's value. Prop being mutated: "text"

大致意思就是在父子组件传值是单向传值,在子组件中进行修改了此值后便会发生以下错误,而我所在子组件使用的v-m-editor组件在输入内容后便会改变text的值,便导致了以上错误

解决方案:

分为多种方案,这里只讲我的解决方案,采用将子组件内所需要的不再使用props里面的属性,而是子组件属性进行替换

export default{props: {text: ""},data(){return {content: ""}},watch:{text: {handler: function (value){this.content = value}}}}

<v-md-editor v-model="content":disabled-menus="[]"@upload-image="handleUploadImage"height="400px"></v-md-editor>

这里我们采用watch监听text的值,发生变化后赋值给content,同时md-editor组件不再使用text属性,而是改用content属性,这样就解决了父子组件单向传值的问题了

踩坑二

本以为这样就解决了,没想到又报error了

[Vue warn]: Error in created hook: "Error: Input data should be a String"

大致意思说呢,应该接受一个String类型的变量,而我给的并不是String,思前想后 恍然大悟,我在新增的时候 传给子组件的text值是null啊!

既然已经发现了错误原因,那离成功就不远了,在经过一阵骚操作(百度)后,终于解决!

export default{props: {text: null},data(){return {content: ""}},watch: {text: {handler: function (value){if (value != this.value){this.content = value == null ? "" : value}}}}}

嗯… 是的,只需要给监听内加个判断就好了,草率了~

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。