简体   繁体   English

Vue2:根据父组件的支持更改子组件的数据属性

[英]Vue2: changing data property of child component based on a prop from a parent component

I have a modal window component in my child component which should be triggered when a user clicks a button in my parent component. 我的子组件中有一个模式窗口组件,当用户单击父组件中的按钮时应触发该窗口组件。 I am passing triggering prop to the child and assigned it to the data property in child component. 我将触发道具传递给孩子,并将其分配给孩子组件中的data属性。 But when button clicked it is not reflected in data property. 但是当单击按钮时,它不会反映在数据属性中。 After searching, a little bit I found the case . 搜索后,我发现了一点情况 But I could not find the solution to my problem. 但是我找不到解决我问题的方法。 I tried with computed properties, but set() of a computed property is being called until it reaches stack overflow! 我尝试使用计算属性,但是将调用计算属性的set()直到达到堆栈溢出! So please could someone provide the best way to achieve my goal: changing data property of child component based on a prop from a parent component 因此,请有人提供实现我目标的最佳方法: 根据父组件的支持更改子组件的数据属性

You can try use the following after code. 您可以尝试在代码后使用以下代码。

 //parent.vue <template> <div class="component"> <p>Ten toi la {{ name }}</p> <p>Toi nam nay {{ age }} tuoi</p> <button @click="resetAge">Reset tuoi</button> <hr> <div class="row"> <div class="col-xs-12 col-sm-6 col-6"> <app-user-detail :age="age" @ageWasUpdated="age = $event"></app-user-detail> </div> </div> </div> </template> <script> import Child from './Child.vue'; export default { data: function () { return { name: 'Duy', age: 23, todo:[ { name:'A', age:12 }, { name:'B', age:13 }, { name:'C', age:14 } ] }; }, components: { appUserDetail: Child, }, methods: { resetAge () { this.age = 23 } } } </script> //child.vue <template> <div class="component"> <h3>User Details</h3> <p>Tuoi toi:{{age}}</p> <button v-on:click="changeAge">Doi tuoi</button> </div> </template> <script> export default { props: ['age'], methods: { changeAge () { this.age = 24; this.$emit('ageWasUpdated', this.age) } } } </script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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