Search code examples
javascriptvue.jsvuex

How to use img src from vuex by looping


I want to call the image source from vuex by looping it in div
I mean like this.

<div v-for="({image}, index) in allData" :key="index">
  <img src="this.image" alt="this.index"/>
</div>

<script>
  import {mapState} from 'vuex';
  export default{
    computed: {
      ...mapState([
        'allData'
      ])
    }
  }
</script>

this is data.js

export default [
  {image: "./image/image1"},
  {image: "./image/image2"},
  {image: "./image/image3"}
]

this is state.js

import data from './data'
export default {data};

this is index.js

import Vue from 'vue'
import Vuex from 'vuex'

import state from './state'

Vue.use(Vuex)

export default new Vuex.Store({state})

enter image description here

thank you


Solution

  • You're missing the double quotes when binding the attribute. Remember that for local images you need to places them into the folder public/assets, then you can change your URLs to assets/your-image-name.jpg. More informations about static assets in Vue.JS can be found here.

    <template>
       <div v-for="({ image }, index) in allData" :key="index">
          <img 
             :src="image" 
             :alt="index"
          />
       </div>
    </template>
    
    <script>
    import { mapState } from 'vuex';
    
    export default {
       computed: {
          ...mapState(['allData'])
       }
    }
    </script>