【问题标题】:VueJS2: Avoid mutating a prop directly since the value will be overwritten whenever the parent component re-rendersVueJS2:避免直接改变道具,因为每当父组件重新渲染时,该值都会被覆盖
【发布时间】:2020-05-21 09:27:53
【问题描述】:

我正在使用Vuejs2 和TailwindCss 创建非常简单的Popup Modal。但是我遇到如下错误,当我想点击Button..

避免直接修改 prop,因为每当父组件重新渲染时,该值都会被覆盖。

In Parent Component

// CardModal

<template>
    <div class="bg-white">
        <div v-if="showing">
            Modal
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            showing: false,
        }
    }
}
</script> 

Child Components

<button  @click="showing = true" class="px-4 my-4 mx-3 bg-blue-400 py-1 font-bold rounded text-white">
    Add Product
</button>

<!-- Modal -->

<cardModal :showing="showing" />

// Script

    props: {
        showing: {
            // required: true,
            type: Boolean,
        }
    },    

提前谢谢...

【问题讨论】:

    标签: vue.js tailwind-css


    【解决方案1】:

    很难理解您的代码,但您不能直接更改子组件中 prop 的值,而是可以向父组件发出一个事件,该事件会为您更改 prop 的值。

    例如,您的子组件具有

    <template>
     @click="$emit('show',true)"
    </template>
    //
     props: {
            showing: {
                // required: true,
                type: Boolean,
            }
        }
    
    

    你的父母

    <cardModal :showing="showing" @show="showing=$event" />
    

    【讨论】:

    • 没有弹出模式... 编辑: 尝试console.log(this.showing),返回false
    猜你喜欢
    • 2017-05-04
    • 2019-09-17
    • 2021-08-12
    • 2019-08-19
    • 2019-04-03
    • 2020-06-01
    • 2017-03-27
    • 2021-09-05
    • 2017-11-28
    相关资源
    最近更新 更多