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



这是我的第一个 Vue 应用程序,所以在代码:P放轻松

我在一侧有一个用户列表,另一侧有一个用于编辑这些用户详细信息的组件。选择用户时,您会看到他们的详细信息,然后可以单击"编辑详细信息"。我想隐藏编辑详细信息,并在选择新用户时显示用户详细信息。在组件内部,我有一个 ShowEdit 变量,它是真或假,将显示或隐藏编辑区域。当选择新用户以隐藏编辑(如果它打开(时,我将父级的 prop 发送到此组件中。我觉得我很接近,因为它目前工作正常,但我想摆脱错误

"避免直接改变道具,因为值将被覆盖 每当父组件重新渲染时...">

以下是重要的部分:

<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行是我进行编辑的地方,但我似乎无法以任何其他方式让它工作。我希望父级能够按照错误的说法覆盖它。有没有办法实现这一点并消除错误?

谢谢。

正如 Nguyun 所说,您可以使用$emit将值发送回父级,以保持值同步。您只能使用 emit 更改父数据,否则当子数据继续进行更改时,它只会保持为真或假。使值与 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>

警告非常明确

在您的子组件中,您正在尝试改变showEditHP的值:

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

但是,不鼓励这种突变。相反,我们应该从子组件emit一个事件,然后让父组件侦听该事件并改变属性本身。

换句话说,属性showEditHP属于父组件,那么父组件应该是改变它的组件。

最新更新