How can I do this in Vue 2?
Solution 1:
In Vue2 there is no setup
function, so instead of:
import { computed, onMounted } from "vue";
import { useStore } from "vuex";
export default {
setup() {
const store = useStore();
const games = computed(() => {
return store.state.gamesFilter.slice(0, 15);
});
onMounted(() => {
store.dispatch("getGames");
});
return {
games,
};
},
};
try to use this
:
export default {
computed: {
games() {
return this.$store.state.gamesFilter.slice(0, 15)
}
},
mounted() {
this.$store.dispatch("getGames");
}
}
var store = new Vuex.Store({
state: {
games: [],
gamesFilter: []
},
mutations: {
setGames(state, payload) {
state.games = payload
},
setGamesFilter(state, payload) {
state.gamesFilter = payload
}
},
actions: {
async getGames({commit}) {
try {
const response = await fetch('https://www.moogleapi.com/api/v1/games/')
const data = await response.json()
commit('setGames', data)
commit('setGamesFilter', data)
} catch (error) {
console.error(error)
}
},
},
});
new Vue({
el: '#demo',
store,
computed: {
games() {
return store.state.gamesFilter.slice(0, 15)
}
},
mounted() {
store.dispatch("getGames");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vuex/2.0.0/vuex.js"></script>
<div id="demo">
<section>
<div class="games">
<div class="games__item" v-for="game in games" :key="game.id">
<h1>{{ game.title }}</h1>
<div>
<img :src="game.picture" :alt="game.name" />
</div>
<span>{{ game.platform }} - {{ game.releaseDate }}</span>
<h3>{{ game.description }}</h3>
</div>
</div>
</section>
</div>