Props实现双向数据绑定

博主使用Mint UI的Tabbar时,遇到子组件无法修改父组件属性值的情况,后放弃该UI库。在Vue2中,子组件修改父组件传递的attr数据会警告。总结了两种不弹出警告的方式,一是父组件通过对象方式传递数据,二是子组件接收数据后通过第三者转换再$emit给父组件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  昨天使用Mint UI的 Tabbar遇到了子组件无法修改父组件的属性值的情况,本菜鸟立马懵逼,没遇到过,网上搜索了一下,还没看懂(菜的真实)。后来看了下这个UI库是两年前的东西了,所以放弃。Vue2.0通过v-model解决

  今天自己写组件的时候遇到了相同的警告,再回看之前搜到的内容,居然醒悟了。

   总结一下,Vue2中,父组件的attr数据,子组件只有读取的权限,修改父组件的传递给子组件的attr数据就会警告。

  不弹出警告

    方式一

      父组件通过对象方式传递数据,思路来源下面的超链接

    方式二

      子组件接收父组件的数据,但是要通过子组件的第三者转换,然后再将修改数据$emit传递给父组件。思路来源自下面超链接

参考资料

对象方式实现

警告内容如下

[Vue warn]: Avoid mutating a prop directly since the value 
will be overwritten whenever the parent component re-renders

 

都是通过green是否为true或false实现样式转变。

  两者的区别是

    通过对象传递,不用绑定事件,调用属性麻烦点。

    通过$emit事件绑定事件麻烦点

方式二的事例

< template>
< div>
< div class= "father" >
父元素
 
</ div>
< child @ changeclass= " changeclass " : green= " green "/>
</ div>
 
</ template>
< script type= "text/javascript">
import child from './components/child.vue'
export default{
components:{
child
},
methods: {
changeclass(){
this. green =! this. green
}
},

data() {
return {
green: true
}
},
}
</ script>
< style lang= "stylus">
.father
width 400 px
height 400 px
background-color pink
</ style>
 
//下面是子组件
 
< template>
< div class= "child" @ click= " changeclass " : class= "{ 'green': green} ">
子元素
</ div>
</ template>
< script type= "text/javascript">
export default{

props:[ "green"],
methods: {
changeclass(){
this. $emit( "changeclass")
}
},
}
</ script>
< style lang= "stylus">
.child
height 200 px
height 200 px
background-color skyblue
& .green
background-color #bfc
 
</ style>

  

方式一的事例

< template>
< div>
< div class= "father" >
父元素
 
</ div>
< child : green= " green "/>
</ div>
 
</ template>
< script type= "text/javascript">
import child from './components/child.vue'
export default{
components:{
child
},
data(){
return { green:{ green: false}}
}
 
}
</ script>
< style lang= "stylus">
.father
width 400 px
height 400 px
background-color pink
</ style>
 
//下面是子组件
 
< template>
 
< div class= "child" @ click= " changeclass " : class= "{ 'green': green. green} ">
子元素
</ div>
</ template>
< script type= "text/javascript">
export default{
 
props:[ "green"],
methods: {
changeclass(){
this. green. green =! this. green. green
    }
},
}
</ script>
< style lang= "stylus">
.child
height 200 px
height 200 px
background-color skyblue
& .green
background-color #bfc
 
</ style>
 

转载于:https://www.cnblogs.com/codylau/p/11166665.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值