在Vue JS外部组件中更改道具

时间:2018-10-05 02:09:22

标签: vue.js

这是我的第一个Vue应用程序,因此在代码上轻松一点:P

我在一侧有一个用户列表,在另一侧有一个编辑这些用户详细信息的组件。选择用户时,您会看到他们的详细信息,然后可以单击“编辑详细信息”。我想隐藏编辑详细信息,并在选择新用户时显示用户详细信息。在组件内部,我有一个ShowEdit变量,它为true或false,将显示或隐藏编辑区域。当选择一个新用户以隐藏编辑(如果打开)时,我将从父级发送一个道具到该组件。我觉得我已经很接近了,因为它目前运行良好,但是我想摆脱错误

  

“避免直接更改道具,因为该值将被覆盖   只要父组件重新呈现。...“

以下是重要的部分:

首页

<transition name="component-fade" mode="out-in">
     <sidebar-client-content :theClient="selectedUser" :showEditHP="showEditHP"></sidebar-client-content>
</transition>

activate: function(el) {
    this.showEditHP = true // Hide edit if new user selected
},

组件

<div id="sidebar-client-content">
<div class="staff_header">
    <a v-if="showEdit" v-on:click="showEdit = !showEdit"><i class="fal fa-edit"></i>Edit</a>
    <a v-if="!showEdit" v-on:click="showEdit = !showEdit"><i class="far fa-times"></i>Close</a>
</div>
<transition-group name="fadeHeight" mode="out-in">
    <div class="client_information" v-if="showEdit">
           <!-- The Client Details -->
    </div>
    <div class="client_information" v-if="!showEdit">
        <!-- Client Edit Form -->
    </div>
</transition-group>
</div>



export default {
props: [
    'showEditHP', // Close edit if new user selected
],
computed: {

    showEdit: {
        get: function() {
            return this.showEditHP
        },
        set: function (newValue) {
            this.showEditHP = newValue
        }
    }

},

我知道进行编辑的地方是this.showEditHP = newValue行,但似乎无法以其他任何方式使它生效。我希望父母能够按照错误所述将其覆盖。有没有办法做到这一点并消除错误?

谢谢。

2 个答案:

答案 0 :(得分:1)

正如Nguyun所说,您可以使用$emit将值发送回父母,以使值保持同步。您只能使用emit更改父数据,否则在孩子继续进行更改时,它只会保持true或false。使值与emit保持同步,然后使用watch来检查父级是否进行了更改。

<transition name="component-fade" mode="out-in">
     <sidebar-client-content @clicked="onClickChild" :theClient="selectedUser" :showEditHP="showEditHP"></sidebar-client-content>
</transition>

onClickChild (value) {
    // I am the child value inside the parent!
},

然后在孩子里

<div class="staff_header">
     <a v-if="showEdit" v-on:click="showEdit = !showEdit; $emit('clicked', showEdit)"><i class="fal fa-edit"></i>Edit</a>
     <a v-if="!showEdit" v-on:click="showEdit = !showEdit; $emit('clicked', showEdit)"><i class="far fa-times"></i>Close</a></i>Close</a>
</div>

答案 1 :(得分:0)

警告很明确

在您的子组件中,您试图更改showEditHP的值:

set: function (newValue) {
    this.showEditHP = newValue
}

但是,不鼓励这种变异。相反,我们应该emit来自子组件的事件,然后让父组件侦听该事件并更改属性本身。

换句话说,属性showEditHP属于父组件,那么父组件应该是对其进行突变的组件。