将值传递给父组件 [英] Passing a value to the parent component
问题描述
子组件如何将其值传递给父组件?这是我的子组件:
Javascript:
new Vue({el: '#table-list',数据: {tableList: ['Empty!'],表已选择:""},方法: {获取表列表(){公理.get('/表格').then(tableList => {this.tableList = tableList.data;}).catch(e => console.warn('获取表列表失败'));},选择表(表){this.tableSelected = table;}},安装(){this.getTableList();}});
HTML:
<p v-for="tableList"><i class="fa fa-table" aria-hidden="true"></i> <span class="text-primary" v-on:click="selectTable(table)">{{ table }} </span></p>
点击时,selectTable
被调用,我想在其父组件中显示值?即我需要将 tableSelected
属性传递给父组件.我怎么能这样做?
你应该使用 vue 组件,特别是 events 机制,用于您要存档的内容.
Props 用于从父组件向子组件传递数据,以及从子组件向父组件发送消息的事件.
<块引用>我们已经了解到父级可以使用 props 将数据传递给子级,但是当发生某些事情时,我们如何与父级通信呢?这就是 Vue 的自定义事件系统的用武之地.
请看这个小提琴https://jsfiddle.net/AldoRomo88/sLo1zx5b/>
我已将您的 selectTable
方法更改为发出自定义事件
selectTable: function(table) {this.$emit('item-changed',table);}
在你的父组件中你只需要监听那个事件
{{selectedItem}}<table-list @item-changed="newValue => selectedItem = newValue " ></table-list>
如果您需要更多说明,请告诉我.
How could a child component pass its value to the parent component? Here is my child component:
Javascript:
new Vue({
el: '#table-list',
data: {
tableList: ['Empty!'],
tableSelected: ""
},
methods: {
getTableList() {
axios
.get('/tables')
.then(tableList => {
this.tableList = tableList.data;
})
.catch(e => console.warn('Failed to fetch table list'));
},
selectTable(table) {
this.tableSelected = table;
}
},
mounted() {
this.getTableList();
}
});
HTML:
<div id="table-list">
<p v-for="table in tableList">
<i class="fa fa-table" aria-hidden="true"></i>
<span class="text-primary" v-on:click="selectTable(table)"> {{ table }} </span>
</p>
</div>
When on click, selectTable
is called, I want to show the value in its parent component? i.e I need to pass tableSelected
property to the parent component. How could I do this?
You should use vue components, specifically events mechanism for what you want to archive.
Props are for pass data from parent to a child components, and events to send messages from child component to parent.
We have learned that the parent can pass data down to the child using props, but how do we communicate back to the parent when something happens? This is where Vue’s custom event system comes in.
Please see this fiddle https://jsfiddle.net/AldoRomo88/sLo1zx5b/
I have changed your selectTable
method to emit a custom event
selectTable: function(table) {
this.$emit('item-changed',table);
}
And in your parent component you just need to listen for that event
<div>
{{selectedItem}}
</div>
<table-list @item-changed="newValue => selectedItem = newValue " ></table-list>
Let me know if you need more clarification.
这篇关于将值传递给父组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!