我创建了一个选择组件JSelect。它获取数组和属性属性以呈现选择组件。属性仅用于选择应在组件中显示数组对象列表中的哪个元素。我基于另一个JSelect组件更改数组数据。第一个列出客户,第二个列出客户的项目。
选择客户和项目然后更改客户时,我清空数据并再次填写。但是,当我在选择项目之前再次选择先前选择的客户时,项目组件将自动选择。由于我在@change事件中获取其值,因此如果不重新选择它就无法获取其值。当只有一个项目要显示时,这是一个大问题。 我想一步一步澄清这个案例。
这是我的Jselect组件。
<script>
export default {
name: "JSelect",
data() {
return {
selectedItem: {},
value: ""
};
},
props: ["arrays", "title", "attribute"],
methods: {
onSelect() {
console.log(this);
this.value = this.selectedItem[
Object.keys(this.selectedItem)[this.attribute]
];
return (this.$emit("changed", this.value));
}
}
};
</script>
<template >
<fieldset class="form-group col-md-4">
<legend class="col-form-label pt-0">{{title}}</legend>
<div>
<select class="custom-select" v-model="selectedItem" @change="onSelect">
<option disabled selected >Select</option>
<option
v-for="(array,index) in arrays"
:value="array"
:key="index"
>{{array[Object.keys(array)[attribute]]}}</option>
</select>
</div>
</fieldset>
</template>
这里是我的用法。
<script>
import Vue from "vue";
import jInput from "@/components/common/jInput";
import jSelect from "@/components/common/jSelect";
export default {
name: "Part",
components: {
jInput,
jSelect
},
data() {
return {
formData: {},
customers: [],
projects: [],
selectProjects: []
};
},
methods: {
projectByCustomer(newCustomer) {
this.selectProjects = [];
this.formData.project = "";
this.formData.customer = newCustomer;
this.projects.map(x => {
if (x.customer === this.formData.customer) {
this.selectProjects.push(x);
}
});
},
onProjectChange(newProject){
this.formData.project = newProject;
}
};
</script>
<template>
<div>
<page-head title="Add Parts" />
<div class="card md-4">
<h6 class="card-header">Add New Part</h6>
<div class="card-body">
<form>
<jSelect
title="Customer"
:arrays="customers"
v-on:changed="projectByCustomer"
attribute="1"
/>
<jSelect
title="Project"
:arrays="selectProjects"
attribute="1"
v-on:changed="(newVal) => {formData.project = newVal}"
/>
</form>
</div>
</div>
</div>
</template>