fix(components): [select-v2] initial value compatibility (#10759)

* fix(components): [select-v2] Initial value compatibility

* chore: simplify logic and add a test case
This commit is contained in:
zz 2022-11-27 22:34:48 +08:00 committed by GitHub
parent 3e9a2c5cd1
commit 4cb900bfc8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 81 additions and 3 deletions

View File

@ -478,6 +478,55 @@ describe('Select', () => {
expect(placeholder.text()).toBe(DEFAULT_PLACEHOLDER)
})
describe('initial value', () => {
it.each([
[null, DEFAULT_PLACEHOLDER],
[undefined, DEFAULT_PLACEHOLDER],
['', ''],
[[], DEFAULT_PLACEHOLDER],
[{}, '[object Object]'],
])(
'[single select] initial value is %s, placeholder is "%s"',
async (value, placeholder) => {
const wrapper = createSelect({
data: () => {
return {
value,
}
},
})
await nextTick()
expect(wrapper.find(`.${PLACEHOLDER_CLASS_NAME}`).text()).toBe(
placeholder
)
}
)
it.each([
[null, DEFAULT_PLACEHOLDER],
[undefined, DEFAULT_PLACEHOLDER],
['', DEFAULT_PLACEHOLDER],
[[], DEFAULT_PLACEHOLDER],
[{}, DEFAULT_PLACEHOLDER],
])(
'[multiple select] initial value is %s, placeholder is "%s"',
async (value, placeholder) => {
const wrapper = createSelect({
data: () => {
return {
multiple: true,
value,
}
},
})
await nextTick()
expect(wrapper.find(`.${PLACEHOLDER_CLASS_NAME}`).text()).toBe(
placeholder
)
}
)
})
describe('multiple', () => {
it('multiple select', async () => {
const wrapper = createSelect({

View File

@ -309,7 +309,15 @@
</template>
<script lang="ts">
import { defineComponent, provide, reactive, toRefs, vModelText } from 'vue'
import {
computed,
defineComponent,
provide,
reactive,
toRefs,
vModelText,
} from 'vue'
import { isArray } from '@element-plus/utils'
import { ClickOutside } from '@element-plus/directives'
import ElTooltip from '@element-plus/components/tooltip'
import ElTag from '@element-plus/components/tag'
@ -340,12 +348,30 @@ export default defineComponent({
],
setup(props, { emit }) {
const API = useSelect(props, emit)
const modelValue = computed(() => {
const { modelValue: rawModelValue, multiple } = props
const fallback = multiple ? [] : undefined
// When it is array, we check if this is multi-select.
// Based on the result we get
if (isArray(rawModelValue)) {
return multiple ? rawModelValue : fallback
}
return multiple ? fallback : rawModelValue
})
const API = useSelect(
reactive({
...toRefs(props),
modelValue,
}),
emit
)
// TODO, remove the any cast to align the actual API.
provide(selectV2InjectionKey, {
props: reactive({
...toRefs(props),
height: API.popupHeight,
modelValue,
}),
popper: API.popper,
onSelect: API.onSelect,
@ -354,7 +380,10 @@ export default defineComponent({
onKeyboardSelect: API.onKeyboardSelect,
} as any)
return API
return {
...API,
modelValue,
}
},
})
</script>