简体   繁体   中英

Are there specific consequences of modifying a parent Array from a child component?

It is possible to modify parents properties from within a child component when the props are an Array:

 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>

Beside the intended action to modify the parent from a child (which may be, style wise, a bad thing to do) - are there collateral consequences of doing so, ones which would break Vue.js?

You will not "break Vue" by breaking encapsulation, and that's what updating a component's data items from outside the component is. The docs say

it is also very important to keep the parent and the child as decoupled as possible via a clearly-defined interface. This ensures each component's code can be written and reasoned about in relative isolation, thus making them more maintainable and potentially easier to reuse.

That is the rationale: it's good programming, not a matter of being something Vue cannot handle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM