iview2 之select二级联动细谈
还是二级联动问题,之前的方法是可以实现二级联动的。但是理想很丰满,现在很骨感。因为后台可能也没法给你理想的数据结构。最后想到办法的利用两个接口拿到数据,实现渲染。直接来代码
<template>
<div class="m-long">
<Form ref="formValidate" :model="formValidate"
:rules="ruleValidate" :label-width="100"
label-position="left">
<FormItem label="一级栏目" prop="categoryIdName">
<Select v-model="formValidate.categoryIdName"
placeholder="请选择一级栏目"
@on-change="changeSecList"
:label-in-value ="true"
style="width:200px">
<Option v-for="item in categoryList" v-if="item.firstname"
:value="item.id" :key="item.id" :label="item.firstname">
{{ item.firstname }}
</Option>
</Select>
</FormItem>
<FormItem label="二级栏目" prop ='name'>
<Select v-model="formValidate.name"
placeholder="请选择二级栏目"
@on-change="getCategoryId"
:label-in-value ="true"
style="width:200px">
<Option v-for="item in secondnameList"
:value="item.id" :key="item.id" :label="item.name">
{{ item.name }}
</Option>
</Select>
</FormItem>
</Form>
</div>
</template>
<script>
import { ruleValidate } from '@/constants/article';
import {
geSecondCategory
} from '@/api/article';
export default {
name: 'long',
props: {
categoryList: { // 父级传来的一级栏目列表
type: Array,
},
allDataList: { // 文章列表
type: Array,
}
},
data() {
return {
secondnameList: [], // 二级栏目列表
formValidate: {
secondname: '',
categoryIdName: '',
categoryId: '',
},
ruleValidate: ruleValidate, // 校验
};
},
methods: {
// 获取二级栏目
changeSecList(val) {
this.formValidate.categoryIdName = val.value
this.geSecondCategory(val.value)
},
async geSecondCategory(id) {
let res = await geSecondCategory(id)
this.secondnameList = res.data.content
},
// 存入二级categoryId
getCategoryId (val) {
this.formValidate.categoryId = val.value
console.log(val.value)
},
// 根据是否有文章ID渲染页面
async init() {
this.articleId = this.$route.query.articleId || '';
if (this.articleId) {
let { data } = await getArticles(this.articleId);
this.formValidate = data;
if (this.allDataList.length) {
this.allDataList.forEach((item, index) => {
if (data.categoryId === item.id) {
this.formValidate.name = data.categoryId
this.formValidate.categoryIdName = item.firstId
this.geSecondCategory(item.firstId)
}
})
} else {
this.init()
}
}
},
},
mounted() {
this.init();
},
};
</script>
遇到的问题与解决方法
1.select默认只返回一个值,但我同时需要firstId与firstname两个参数。解决方法:label-in-value(是否将 label 和 value 一并返回,默认只返回 value),这个api主要帮我实现将firstId传给获取二级栏目当参数,firstname传给保存接口。
2.渲染问题:1)没注意:key这个参数。写的是:key="item.firstId"结果死活都渲染不出我想要的数据。因为在没使用:label这个api是没有任何问题的,最后仔细想想原来对象渲染的问题key与value当然要对应不然怎么实现渲染,想打自己。
2)on-change事件中选中的Option变化时触发,默认返回 value,如需返回 label,详见 label-in-value 属性。这是官网给写的解释,所以:label应该显示firstname,那:value与:key就得用id与进行匹配。
3)当文章是处于编辑状态,当然要把文章渲染进来。可是由于生命周期的原因一开始拿不到父级传的数据,有考虑过数组更新没渲染的问题,使用$set去解决。但并没效果,就想到了如果没有获取到数据就再次渲染直到拿到数据。终于搞定。不知道哪位大 佬有更好的解决方案。
当解决完这些问题,都觉得好简单,但是当时可不是这种想法。到这里,所有的事情都解决,等待上线。

浙公网安备 33010602011771号