javascript - 组件的 v-for 循环中的选定值
问题描述
我实现了一个内部有一个选择元素的组件,它或多或少类似于以下内容:
<!-- child component -->
<template>
<b-form-select
v-model="selectedProject"
:options="projects"
@change="changedValue">
<template v-slot:first>
<option :value="null" disabled>-- Please select a project --</option>
</template>
</b-form-select>
</template>
<script>
export default {
name: 'AllocationItem',
props: {
projects: {
type: Array,
default: () => [{ value: Number}, { text: String}]
}
},
data() {
return {
selectedProject: null,
}
},
methods: {
changedValue(value) {
this.selectedProject = value;
}
}
}
</script>
我在父组件中使用此组件,可以在其中添加其他 AllocationItem 单击按钮。
为此,我使用了一个数组,每次点击添加按钮时我都会推送一个新项目(我不知道这是否是正确的方式......)
遵循父组件代码:
<!-- parent component -->
<template>
<b-button class="btnAction" @click="addItem()">Add</b-button>
<b-button class="btnAction" @click="sendAllocation()">Send</b-button>
<b-row v-for="allocation in resourceItem.allocations" v-bind:key="allocation.id">
<allocation-item v-bind:projects="projects"></allocation-item>
</b-row>
</template>
<script>
export default {
name: 'Management',
components: {
AllocationItem
},
data() {
return {
allocations: []
}
},
methods: {
addItem() {
this.allocations.push(AllocationItem);
},
sendAllocation() {
this.allocations.forEach((allocation) => {
// I WOULD LIKE TO HAVE ALL SELECTED VALUE HERE!!!
});
},
},
created() {
const dataProjects = this.getProjectsData();
dataProjects.then(response => {
this.projects = response.map((item) => {
return {value: item.id, text: item.name}
})
});
}
</script>
在我的应用程序中,我有另一个按钮,发送按钮,应该读取在所有子组件(分配项)中选择的值。
我该怎么做才能拥有一个具有该选定值的数组?
提前谢谢大家
解决方案
首先,问问自己这个组件是否在除此处以外的其他任何地方使用。如果你只使用一次,把它构建到父组件中,你的问题就解决了。否则我会选择@laurensvm 的使用 emit 或 Vuex 的方法。
推荐阅读
- unreal-engine4 - 虚幻错误:使用 -cook 或 -cookonthefly 需要游戏目标
- android - 全局保存数据并访问 android studio 中的各种活动
- responsive-design - 如何使用媒体查询缩小此导航菜单
- c# - 应用程序窗口未聚焦时如何在 UWP 中更改\控制鼠标位置?
- ios - Swift:旋转 UIImage 并填充它
- c++ - Windows 7 GetLastError 87 中的 UpdateLayeredWindow 失败
- javascript - WIX Fetch API 返回空 JSON (VELO)
- swift - 无法将“()”类型的返回表达式转换为“凭据”类型
- flutter - 仅文本 Flutter 的命中测试
- c++ - GCC 的 type_traits 实现是不好的做法吗?