Home > Software engineering >  Change view by using computed property
Change view by using computed property

Time:09-01

I have component of ViewControls, where have switchControls with which I can get the index of the clicked button. For example, i clicked first btn, and snippetValue will be 0, and so on.

    <template>
    <SwitchControls v-model="snippetValue">
      <button>
        <i  />
      </button>
      <button>
        <i  />
      </button>
    </SwitchControls>
    </template>

Question, how can i bind to a snippetValue (0 - 'list', 1 - 'grid') and emit params

   emits: [ "update:modelValue" ],
    setup (props, { emit }) {
     const snippetValue = ref(0)

     const currentValue = computed({
       get: () => props.modelValue,
       set: (val: number) => {
         if (val === 0) {
           emit("update:modelValue", "list")
         }
         else {
           emit("update:modelValue", "grid")
         }
       },
     })
    },

parent.vue

   <ViewControls v-model="snippetVariant"/>

CodePudding user response:

Try to bind the v-model directive from SwitchControls directly with computed property currentValue :

    <template>
    <SwitchControls v-model="currentValue">
      <button>
        <i  />
      </button>
      <button>
        <i  />
      </button>
    </SwitchControls>
    </template>

 emits: [ "update:modelValue" ],
    setup (props, { emit }) {
     const currentValue = computed({
       get: () => props.modelValue,
       set: (val: number) => {
           emit("update:modelValue", val === 0 ? "list" : "grid")
       },
     })
    },
  • Related