Props实现双向数据绑定

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

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

   总结一下,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>
 

猜你喜欢

转载自www.cnblogs.com/codylau/p/11166665.html
今日推荐