更改子组件中的布尔值

问题描述 投票:0回答:1

在 React 中,我能够使用 prop 中的

useState
来更新子组件的布尔值,以来回传递新值,但是在 Vue 中,我很难做到类似的事情。

我已经能够通过这样做将布尔值传递给子组件:

家长:

<template>
  <button @click="viewProduct()"
  <ChildComponent v-if="showProduct === true" :showProduct = showProduct />
</template>

<script setup>
  import { ref, defineProps } from 'vue'
  import ChildComponent from './ChildComponent.vue'
  
  let showProduct = ref(false)
  const viewProduct = (e) => {
      showProduct.value = true
  }
</script>

我可以看到作为 prop 传递给子组件的值,我可以在子组件中使用它。

但是,如果我尝试使用以下内容更改子组件中的变量:

孩子:

<template>
  <div class="close" @click="hidePDP()">X</div>
</template>

<script setup>
    import { defineProps, computed } from 'vue'
    
    const props = defineProps({
        showProduct: Boolean,
    });
    
    const hidePDP = computed( () => {       
        return props.showProduct = false
    });
</script>

我收到这些错误,我猜道具即使它们已经是

ref()
值仍然不喜欢你改变它们。

60:16  error  Unexpected mutation of "showProduct" prop    vue/no-mutating-props
60:16  error  Unexpected side effect in computed function

但是,我无法成功找到一种方法来更新子组件中的布尔值(反转布尔值),以便当在子组件中单击关闭按钮时,父组件可以从渲染中删除

ChildComponent
元素本身。

我希望这是有道理的,我已经看到了一些问题,讨论如何获得帮助以反向从父级(我已经开始工作)向子级发送道具数据,例如 props value not send theupdated value从 vue 中的父组件到子组件在 vue.js 中的子组件中创建传递的 props 的本地副本?,但不是上述问题的确切答案。

javascript vue.js
1个回答
0
投票

我在您提供的代码中发现两个主要错误。 首先,你试图改变 prop,其次你除了计算计算值之外什么都做不了。

vue 中的最佳实践是将 prop 发送到 ChildComponent 并监听它的发出并在父组件中进行变异。

父组件:

<template>
  <button @click="viewProduct()">click me</button>
  <ChildComponent v-if="showProduct" @close="onHidePDP" />
</template>

<script setup>
  import { ref, defineProps } from 'vue'
  import ChildComponent from './ChildComponent.vue'
  
  let showProduct = ref(false)
  const viewProduct = (e) => {
      showProduct.value = true
  }
  const onHidePDP = (e) => {
      showProduct.value = false; //we always pass false. So I didn't use event
  }
</script>

孩子:

<template>
  <div class="close" @click="close">X</div>
</template>

<script setup>
    const emit = defineEmits(['close']); // the same as $emit in the template. It can be written in the template `<div class="close" @click="$emit('close')">X</div>` without this setup functions
    function close () {
      emit('close')
    }
</script>

有用的链接:

https://vuejs.org/guide/components/events.html#component-events

https://vuejs.org/guide/essentials/compulated.html#getters-should-be-side-effect-free

如果您的组件应该双向绑定,请查看组件的 v-model: [https://vuejs.org/guide/components/v-model.html#component-v-model

© www.soinside.com 2019 - 2024. All rights reserved.