vue3子组件改变父组件的值(props)reactive和ref的区别

其实关于子组件改变父组件的值,直接改是不可以的,我们一般通过绑定事件来改变,但是如果是reactive里面的复杂数据类型,我们只要不改变其内存地址,是可以改变复杂数据类型里面的值的

下面看相关代码,父子组件的层级如图

父组件代码:

<template>
  <h1>ref定义的值{{refNum}}</h1>
  <h1>reactive定义的值{{reactiveNum}}</h1>
  <h1>reactive定义的数组{{reactiveArr}}</h1>
  <little
    :refNum="refNum"
    :reactiveNum="reactiveNum"
    :reactiveArr="reactiveArr"
  ></little>
</template>

<script>
import little from './little'
import { toRefs, reactive, ref } from 'vue'
export default {
  name: "big",
  components: { little },
  setup () {
    const refNum = ref(0)// 不能直接通过子组件改变
    const reactiveObj = reactive({
      reactiveNum: 0,  // 不能直接通过子组件改变
      reactiveArr: [1, 2, 3]  // 不改变内存地址,可以通过子组件之间改变里面的值
    })
    return {
      refNum,
      ...toRefs(reactiveObj)
    }
  }
}
</script>

<style>
</style>

子组件

<template>
  <button @click="changeRefVal">点我改变ref的值</button>
  &nbsp;&nbsp;
  <button @click="changeReactiveVal">点我改变reactive的值</button>
  &nbsp;&nbsp;
  <button @click="changeReactiveArr">点我改变reactive的数组</button>
</template>

<script>
export default {
  name: "little",
  props: ["refNum", "reactiveNum", "reactiveArr"],
  setup (props, context) {
    // 改变 ref 的值
    const changeRefVal = () => {
      props.refNum++ // 报警告,不生效
    }
    // 改变 reactive 里面的值
    const changeReactiveVal = () => {
      props.reactiveNum++ // 报警告,不生效
    }
    // 改变 reactive 里面的数组
    const changeReactiveArr = () => {
      //   props.reactiveArr = [1, 2, 3, 4]  // 报警告,不生效
      props.reactiveArr.push(4) // 生效
    }
    return {
      changeRefVal,
      changeReactiveVal,
      changeReactiveArr
    }
  },
}
</script>

<style>
</style>

  • 9
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3中,可以通过使用`ref`或`reactive`来创建响应式数据,并通过props将其传递给组件。要清空组件,可以通过重置组件中的响应式数据来实现。 下面是一个示例: ```vue <template> <div> <button @click="resetChildValue">清空组件</button> <ChildComponent :value="parentValue" /> </div> </template> <script> import { ref } from 'vue'; import ChildComponent from './ChildComponent.vue'; export default { components: { ChildComponent }, setup() { // 创建响应式数据 const parentValue = ref(''); // 清空组件 const resetChildValue = () => { parentValue.value = ''; }; return { parentValue, resetChildValue }; } }; </script> ``` 在组件中,我们使用`ref`来创建`parentValue`作为响应式数据,并将其传递给组件`ChildComponent`。通过点击按钮时调用`resetChildValue`方法,我们可以将`parentValue`重置为空字符串,从而清空组件。 请注意,此示例假设组件是通过props接收组件,并在组件内部进行更新。组件的实现可能如下所示: ```vue <template> <div> <input type="text" v-model="value" /> </div> </template> <script> export default { props: { value: { type: String, required: true } } }; </script> ``` 在组件中,我们使用`value`作为props接收组件,并将其绑定到input元素的v-model上,以实现双向绑定。当组件的`parentValue`更新时,组件也会相应更新。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值