還是二級聯動問題,之前的方法是可以實現二級聯動的。但是理想很豐滿,現在很骨感。因為后台可能也沒法給你理想的數據結構。最后想到辦法的利用兩個接口拿到數據,實現渲染。直接來代碼
<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去解決。但並沒效果,就想到了如果沒有獲取到數據就再次渲染直到拿到數據。終於搞定。不知道哪位大 佬有更好的解決方案。
當解決完這些問題,都覺得好簡單,但是當時可不是這種想法。到這里,所有的事情都解決,等待上線。
