Search code examples
javascriptvue.jsvuexv-for

VueJS filter for v-for to v-if


I have the following filter


  computed: {
    ...mapState({
      myNodes: (state) => state.myNodes,
      configPositions: (state) => state.configPositions,
      configEmoji: (state) => state.configEmoji,
    }),

    nodes_filtered: function () {
      return this.myNodes.filter((nodes) => {
        return nodes.deleted == false
      })
    },

    emojis_filtered() {
      return this.configEmoji.filter((emojis) => {
        // console.log(emojis)
        // if emojis.nodeid == myNodes.node_id
        return emojis
      })
    },

}

My template


    <div v-for="(nodes, index) in nodes_filtered" v-bind:key="index">
      <form class="nodes">
        <textarea
          @focus="editTrue(true)"
          @blur="editTrue(false)"
          autofocus
          v-model="nodes.node_text"
          @input="editNode"
          :id="nodes.node_id"
          placeholder="Type your thoughts and ideas here! (auto saved every keystroke)"
        ></textarea>
        <p class="info">*markdown supported &amp; autosaves</p>

        <div class="btn-row">
          <SvgButton
            buttonClass="nodes"
            @click.prevent="deleteFlag(value.node_id)"
          />
          <SvgButton2 buttonClass="nodes" @click.prevent="readFlag()" />
        </div>

        <div class="allemoji">
          <div
            class="eachemoji"
            v-for="(emojis, index) in emojis_filtered"
            :key="index"
          >
            {{ emojis.emoji_text }}
          </div>
        </div>
      </form>
    </div>

This is working but what I need is to filter the emojis differently, so that the emojis only show on the correct text and I am not sure on the correct syntax that would be if emojis.nodeid == myNodes.node_id and thus display in that form. This is to about avoiding the bad practice of using v-if inside a v-for.


Solution

  • The bad practice is to use v-if and v-for in the same element, but the following syntax is allowed :

    <div
                class="eachemoji"
                v-for="(emojis, index) in emojis_filtered"
                :key="index"
              >
                <template v-if="emojis.nodeid == nodes.node_id">{{ emojis.emoji_text }}</template>
              </div>
    
    

    or make the computed like :

        emojis_filtered() {
          return this.configEmoji.filter((emojis) => {
            return  this.myNodes.some(node=>emojis.nodeid == node.node_id)
          })
        },