3

当传递的道具对象中的嵌套属性发生更改时,我无法更新计算属性。

this.favourite是通过 props 传递的,但是当this.favourite.selectedChoices.second.idthis.favourite.selectedChoices.first.id更改时,计算的属性不会更新。

关于如何使这种反应的任何想法?

这是计算的属性:

isDisabled() {
  const hasMultipleChoices = this.favourite.choices.length
    ? this.favourite.choices[0].value.some(value => value.choices.length) : 
    false;

  if (hasMultipleChoices && !this.favourite.selectedChoices.second.id) {
    return true;
  } else if (this.favourite.choices.length && !this.favourite.selectedChoices.first.id) {
    return true;
  }

  return false;
}
4

2 回答 2

2

经过测试

在我的 test.vue

props: {
    variant: {
      type: String,
      default: ''
    }
}

const myComputedName = computed(() => {
  return {
    'yellow--warning': props.variant === 'yellow',
    'red--warning': props.variant === 'red',
  }
})

test.spec.js

    import { shallowMount } from '@vue/test-utils'
    import test from '@/components/test.vue'
    let wrapper
    
    //default values
    function createConfig(overrides) {
      let variant = ''
      const propsData = { variant }
      return Object.assign({ propsData }, overrides)
    }
    //test
    describe('test.vue Implementation Test', () => {
      let wrapper
    
      // TEARDOWN - run after to each unit test
      afterEach(() => {
        wrapper.destroy()
      })
      it('computed return red if prop variant is red', async (done) => {
        const config = createConfig({ propsData: { variant: 'red' } })
        wrapper = shallowMount(test, config)
        wrapper.vm.$nextTick(() => {
        //checking that my computed has changed, in my case I want to matchanObject
          expect(wrapper.vm.myComputedName).toMatchObject({
            'red--warning': true
          })
          //check what your computed value looks like
          console.log(wrapper.vm.myComputedName)
          done()
        })
      })

//TEST 2 Variant, this time instead red, lets say yellow

      it('computed return yellow if prop variant is red', async (done) => {
        const config = createConfig({ propsData: { variant: 'yellow' } })
        wrapper = shallowMount(test, config)
        wrapper.vm.$nextTick(() => {
        //checking that my computed has changed, in my case I want to matchanObject
          expect(wrapper.vm.myComputedName).toMatchObject({
            'yellow--warning': true
          })
          //check what your computed value looks like
          console.log(wrapper.vm.myComputedName)
          done()
        })
      })
    })

有关更多信息,此页面对我有所帮助。

https://vuejsdevelopers.com/2019/08/26/vue-what-to-unit-test-components/

于 2021-02-03T14:51:50.420 回答
1

计算属性没有更新的原因是因为我在渲染组件后创建了this.favourite.selectedChoices.secondthis.favourite.selectedChoices.first的 id 对象。在渲染之前声明 id 对象是解决方案。

于 2019-01-08T11:25:27.563 回答