vue.jsconditional-rendering

VueJS Conditional rendering with v-show and json


I'm building a portfolio with VueJs and would display projects with selected tags.

Here is my code:

<script lang="ts">
  import projectsData from "../projects.json"

  export default {
    
    data() {
        return {
          projects: projectsData,
          selectedTags: []
        }
      }
  }
</script>

<template>
  <div class="works">
    <h1> Discover my works </h1>
    <div class="tags-container"> 
      <input type="checkbox" id="web_dev" value="Web development" v-model="selectedTags">
      <label for="Web development">Web Development</label>

      <input type="checkbox" id="web_design" value="Web design" v-model="selectedTags">
      <label for="Web design">Web Design</label>
    </div>

    <div class="works-container">
      <div v-for="project in projects" :key="project.id" :tags="project.tags" :selected-tags="selectedTags" v-show="selectedTags == project.tags"  class="single-project"> {{ project.title }} </div>
    </div>
  </div>
</template>

I want to display project with this condition: if selectedTags equals my project tags so it displays it.

Even if my tags are equals, it doesn't display my project but I don't understand why ?

Can someone explain this to me?

Thanks


Solution

  • You cannot check content equality of two arrays with === (or ==) in Javascript. A condition like selectedTags == project.tags will only be true if both variables point to the same array instance.

    You will have to check the elements individually:

    selectedTags.length === project.tags.length && selectedTags.every(tag => project.tags.includes(tag))
    

    const arr1 = [1,2,3]
    const arr2 = [1,2,3]
    const arr3 = arr1
    
    console.log('Same content different instance is equal:', arr1 == arr2)
    console.log('Same instance is equal:', arr1 == arr3)
    
    const sameContent = arr1.length === arr2.length && arr1.every(tag => arr2.includes(tag))
    console.log('Same elements in different instances:', sameContent)