Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use Vue and Array to make a conditions

I have values XS S M loaded as HTML for all sizes Black White and I have a JSON show available sizes of each color.

I want to add v-if when the XS is not available in the array variant_selection.size by using variant_selection.option1 and the values that loaded as HTML XS S M.

Example:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 variant_selection: {
          option1: "Black",
          option2: "XS",
          size: [
          "Black / XS", /// Only black color has XS size
          "Black / S",
          "Black / M",
          "White / S",
          "White / M",
          ],
        },

I was trying that but didn’t work for me, please help

<span v-if="'variant_selection.option1 / {{ value }}' !== 'variant_selection.size.includes(variant_selection.option1) / {{ value }}' ">.</span>

>Solution :

<span v-if="variant_selection.size.includes(variant_selection.option1 + ' / ' + value)" ..

or

<span v-if="variant_selection.size.includes(`${variant_selection.option1} / ${value}`)" ..

You should not use Mustaches {{}} in the Vue v-if conditions

See, Attribute Bindings

Mustaches cannot be used inside HTML attributes. Instead, use a
v-bind directive

Solution

const { createApp,ref } = Vue

const App = {
  setup() {
    const color = ref('')
    const colors = ['Black','White']
    const size = ref('')
    const sizes = ['XS','S', 'M']
    const selection =  {
          size: [
          "Black / XS", /// Only black color has XS size
          "Black / S",
          "Black / M",
          "White / S",
          "White / M",
          ]
    }
    return {
      color, colors, size, sizes, selection
    }
  }
}

const app = createApp(App)
app.mount('#app')
#app { line-height: 1.75; }
[v-cloak] { display: none; }
<div id="app" v-cloak>
  Color: <select v-model="color">
  <option v-for="c in colors">{{c}}</option>
  </select><br/>
  Size: <select v-model="size">
  <option v-for="s in sizes">{{s}}</option>
  </select><br/>
  Combination: {{ `${color} / ${size}` }}<br/>
  <span v-if="selection.size.includes(`${color} / ${size}` )">Combination is present</span>
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading