父子组件传值错误

本文介绍了在Vue中父子组件通信时遇到的问题,即子组件直接修改了从父组件接收到的props值。这违反了Vue的单向数据流原则,导致错误。为了解决这个问题,文章提供了修改后的代码示例,通过使用computed属性的setter方法,使得子组件能够正确地通知父组件改变props值,而不是直接修改。这一改变确保了数据流动的正确方向,遵循了最佳实践。
摘要由CSDN通过智能技术生成

父组件使用 addFriendVisible 传值给子组件的 props 属性

<template>
    <div>
      <add-friend @addFriendClose="addFriendClose" :addFriendVisible="addFriendVisible" />
    </div>
</template>
<script>
import addFriend from '@/components/AddFriend'
export default {
  name: 'AddressBook',
  components: {addFriend},
  data () {
    return {
      addFriendVisible: false
    }
  },
  methods: {
    addFriendClose () {
      this.addFriendVisible = false
    },
    handleCommand (command) {
      if (command === '0') {
        console.log('加入群聊≡ω≡')
        this.addGroupVisible = true
      } else if (command === '1') {
        console.log('添加好友︿( ̄︶ ̄)︿')
        this.addFriendVisible = true
      } else if (command === '2') {
        console.log('发起群聊( ̄▽ ̄)~■干杯□~( ̄▽ ̄)')
        this.newGroupVisible = true
      } else {
        this.$message.error('错了哦,这是一条错误消息╮(╯▽╰)╭')
      }
    }
  }
}

子组件封装了 elementui 的 dialog 组件,且是嵌套的 dialog 组件,在子组件中我们拿到了父组件传来的 props : addFriendVisible,并直接用于组件的显示,在点击确定时我们会在子组件中发送给父组件消息 this.$emit('addFriendClose') 来让父组件关闭子组件

<template>
    <el-dialog title="添加好友" :visible.sync="addFriendVisible" width="36%">
    <el-dialog
        width="30%"
        title="申请添加好友"
        :visible.sync="innerFriendVisible"
        append-to-body>
        <el-input v-model="additionMessage" placeholder="添加验证消息"></el-input>
        <div class="validateForm">
            <el-button size="small" type="success" @click="addFriend()">确 定</el-button>
            <el-button size="small" @click="innerFriendVisible=false">取 消</el-button>
        </div>
    </el-dialog>
    </el-dialog>
</template>
<script>
export default {
  name: 'AddFriend',
  props: [ 'addFriendVisible' ],
  data () {
    return {
      innerFriendVisible: false,
      friendObj: {},
    }
  },
  methods: {
    // 设置添加好友消息
    setFriend (friendInfo) {
      this.friendObj = friendInfo
      this.innerFriendVisible = true
    },
    // 发送添加好友消息
    addFriend () {
      this.innerFriendVisible = false
      this.$emit('addFriendClose')
    }
  }
}
</script>

看起来还是合理的,但是报错

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: "addFriendVisible"
避免直接改变组件,因为每当父组件重新渲染时,该值将被覆盖。相反,使用基于组件值的数据或计算属性。组件改变:“addFriendVisible”

产生错误的原因

props 是父向子传值的一种形式。当我们子组件的 props 值要改变的时候,不能直接通过改变子组件的 props 来改变父组件。而现在就相当于是我们在反向改变 props,因为值已经被双向绑定了

修改后代码

父组件

<template>
    <div>
      <add-friend @addFriendClose="addFriendClose" @changeAddFriendVisible="changeAddFriendVisible" :addFriendVisible="addFriendVisible" />
    </div>
</template>
<script>
import addFriend from '@/components/AddFriend'
export default {
  name: 'AddressBook',
  components: {addFriend},
  data () {
    return {
      addFriendVisible: false
    }
  },
  methods: {
    changeAddFriendVisible (val) {
      this.addFriendVisible = val
    },
    addFriendClose () {
      this.addFriendVisible = false
    },
    handleCommand (command) {
      if (command === '0') {
        console.log('加入群聊≡ω≡')
        this.addGroupVisible = true
      } else if (command === '1') {
        console.log('添加好友︿( ̄︶ ̄)︿')
        this.addFriendVisible = true
      } else if (command === '2') {
        console.log('发起群聊( ̄▽ ̄)~■干杯□~( ̄▽ ̄)')
        this.newGroupVisible = true
      } else {
        this.$message.error('错了哦,这是一条错误消息╮(╯▽╰)╭')
      }
    }
  }
}

子组件

  • 我们将传进来的值与真正使用的值分开,使用 computed 属性来为其传值
<template>
    <el-dialog title="添加好友" :visible.sync="sonAddFriendVisible" width="36%">
    <el-dialog
        width="30%"
        title="申请添加好友"
        :visible.sync="innerFriendVisible"
        append-to-body>
        <el-input v-model="additionMessage" placeholder="添加验证消息"></el-input>
        <div class="validateForm">
            <el-button size="small" type="success" @click="addFriend()">确 定</el-button>
            <el-button size="small" @click="innerFriendVisible=false">取 消</el-button>
        </div>
    </el-dialog>
    </el-dialog>
</template>
<script>
export default {
  name: 'AddFriend',
  props: [ 'addFriendVisible' ],
  data () {
    return {
      innerFriendVisible: false,
      friendObj: {},
    }
  },
  computed: {
    sonAddFriendVisible: {
      get () {
        return this.addFriendVisible
      },
      set (val) {
        this.$emit('changeAddFriendVisible', val)
      }
    }
  },
  methods: {
    // 设置添加好友消息
    setFriend (friendInfo) {
      this.friendObj = friendInfo
      this.innerFriendVisible = true
    },
    // 发送添加好友消息
    addFriend () {
      this.innerFriendVisible = false
      this.$emit('addFriendClose')
    }
  }
}
</script>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在React中,父组件向子组件传值可以通过props来实现。父组件可以将需要传递的数据作为属性传递给子组件,子组件通过props来接收这些数据。下面是几种常见的父子组件传值的方式: 1. 父组件通过props传递数据给子组件: 父组件定义一个属性,并将需要传递的数据作为该属性的值,然后将子组件引入到父组件中,并将该属性作为子组件的一个属性传递进去。子组件可以通过props来接收并使用这个数据。例如,父组件中定义属性`txt0`,并将它传递给子组件`Child`: ```javascript <Child txt={this.state.txt0} /> ``` 子组件可以通过props来接收并使用父组件传递的数据: ```javascript this.props.txt ``` 2. 父组件通过回调函数传递数据给子组件: 父组件定义一个回调函数,并将该函数作为属性传递给子组件。子组件可以通过调用这个回调函数,将需要传递的数据作为参数传递给父组件。例如,父组件中定义一个回调函数`getDatas`: ```javascript getDatas(msg){ this.setState({ mess: msg }); } ``` 然后将该函数作为属性传递给子组件`Son`: ```javascript <Son getdata={this.getDatas.bind(this)}></Son> ``` 子组件可以通过调用父组件传递的回调函数,并将需要传递的数据作为参数传递给它: ```javascript this.props.getdata(data); ``` 3. 父组件通过context传递数据给子组件: Context是React提供的一种跨组件传递数据的机制。父组件可以通过定义一个Context,并将需要传递的数据放在Context中,然后子组件可以通过访问Context来获取这些数据。具体的实现可以参考React官方文档中关于Context的介绍。 以上是React中父子组件传值的几种常见方式,你可以根据具体的需求选择合适的方式来实现父子组件之间的数据传递。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* [React父子组件间的传值的方法](https://download.csdn.net/download/weixin_38595850/13633672)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *2* [React教程:父子组件传值组件通信)](https://blog.csdn.net/p445098355/article/details/104519363)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] - *3* [React父子组件传值](https://blog.csdn.net/weixin_45817109/article/details/103628428)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 33.333333333333336%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值