gpt4 book ai didi

javascript - 从子组件修改父数组是否有特定的后果?

转载 作者:搜寻专家 更新时间:2023-10-30 22:27:15 25 4
gpt4 key购买 nike

props 出现时,可以从子组件中修改父属性。是一个数组:

Vue.component('search-box', {
template: '#search-box-template',
props: ['who']
})
var vm = new Vue({
el: '#root',
data: {
who: ['a', 'b']
}
})
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.3.3/vue.js"></script>

<div id="root">
who as seen by the parent: {{who}}
<search-box v-bind:who="who"></search-box>
</div>

<template id="search-box-template">
<div>
who as seen by the child: {{who}}
<button v-on:click="who.push('x')">modify who from within the child</button>
</div>
</template>

除了从子项修改父项的预期操作(从风格上讲,这可能是一件坏事)——这样做是否会产生附带后果,即会破坏 Vue.js 的后果?

最佳答案

您不会通过破坏封装来“破坏 Vue”,这就是从组件外部更新组件的数据项。 docs

it is also very important to keep the parent and the child asdecoupled as possible via a clearly-defined interface. This ensureseach component’s code can be written and reasoned about in relativeisolation, thus making them more maintainable and potentially easierto reuse.

这就是基本原理:这是很好的编程,而不是 Vue 无法处理的问题。

关于javascript - 从子组件修改父数组是否有特定的后果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44429095/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com