diff --git a/src/picker/PickerColumn.js b/src/picker/PickerColumn.js index df436e9ed..21c480721 100644 --- a/src/picker/PickerColumn.js +++ b/src/picker/PickerColumn.js @@ -73,6 +73,8 @@ export default createComponent({ }, watch: { + initialOptions: 'setOptions', + defaultIndex(val) { this.setIndex(val); }, @@ -89,6 +91,13 @@ export default createComponent({ }, methods: { + setOptions(options) { + if (JSON.stringify(options) !== JSON.stringify(this.options)) { + this.options = deepClone(options); + this.setIndex(this.defaultIndex); + } + }, + onTouchStart(event) { this.touchStart(event); diff --git a/src/picker/index.js b/src/picker/index.js index 37ddf2abd..180dd149f 100644 --- a/src/picker/index.js +++ b/src/picker/index.js @@ -182,12 +182,9 @@ export default createComponent({ // set options of column by index setColumnValues(index, options) { const column = this.children[index]; - if ( - column && - JSON.stringify(column.options) !== JSON.stringify(options) - ) { - column.options = options; - column.setIndex(0); + + if (column) { + column.setOptions(options); } }, diff --git a/src/picker/test/index.spec.js b/src/picker/test/index.spec.js index 61377f3f0..542644f96 100644 --- a/src/picker/test/index.spec.js +++ b/src/picker/test/index.spec.js @@ -262,3 +262,37 @@ test('cascade columns', () => { 'Gulou', ]); }); + +test('watch columns change', () => { + const wrapper = mount(Picker, { + propsData: { + showToolbar: true, + columns: ['1', '2'], + defaultIndex: 1, + }, + }); + + wrapper.setProps({ + columns: ['2', '3'], + }); + + wrapper.find('.van-picker__confirm').trigger('click'); + expect(wrapper.emitted('confirm')[0]).toEqual(['3', 1]); +}); + +test('should not reset index when columns unchanged', () => { + const wrapper = mount(Picker, { + propsData: { + showToolbar: true, + columns: ['1', '2'], + }, + }); + + wrapper.vm.setIndexes([1]); + wrapper.setProps({ + columns: ['1', '2'], + }); + + wrapper.find('.van-picker__confirm').trigger('click'); + expect(wrapper.emitted('confirm')[0]).toEqual(['2', 1]); +});