data(){ return{ Item: { ...
v-model="item.name"
ADD_TO_PRODUCTS({commit}, item){ commit('SET_PRODUCT_TO_STATE', item) },
methods:{ ...mapActions([ 'ADD_TO_PRODUCTS', ]),
@click="ADD_TO_PRODUCTS"
state: {
pokemons: [],
next: 'https://pokeapi.co/api/v2/pokemon',
},
actions: {
async fetchPokemons({ state, commit }) {
const data = await fetch(state.next).then(r => r.json());
commit('setPokemons', {
pokemons: data.results,
next: data.next,
});
}
},
<button
:disabled="!$store.state.next"
@click="$store.dispatch('fetchPokemons')"
>
NEXT
</button>
rangeValues: { ...this.$store.state.CarSetup },
Object.entries(newValue).forEach(([ k, v ]) => {
if (v !== oldValue[k]) {
this.$store.commit('setCarInfo', { to: k, value: v });
}
});
computed: {
rangeValues() {
return new Proxy(this.$store.state.carSetup, {
set: (target, key, val) => {
this.$store.commit('setCarInfo', { [key]: val });
return true;
},
});
},
},
setCarInfo: (state, payload) => Object.assign(state.carSetup, payload),
По клику на кнопку вызывается мутация, в которою передаётся id.
Я так понимаю, потому что метод возвращает только false/true, а не измененный item.
id передается, проверял через консоль
...mapMutations(['chekedItem', 'deleteItem']), itemSucces(id) { this.chekedItem({id}); },
chekedItem: (state, item) => item.checked = !item.checked,
state: {
characters: [],
page: 0,
pages: 0,
},
mutations: {
setCharacters: (state, { characters, pages, page }) =>
Object.assign(state, { characters, pages, page }),
},
actions: {
async fetchCharacters({ commit }, page = 1) {
try {
const { data: { info, results } } = await axios.get(`${BASE_URL}?page=${page}`);
commit('setCharacters', {
page,
pages: info.pages,
characters: results,
});
} catch (e) {
console.error(e);
}
},
},
computed: {
currentPage: {
get() {
return this.$store.state.page;
},
set(page) {
this.$store.dispatch('fetchCharacters', page);
},
},
},
<el-pagination
v-model:current-page="currentPage"
:page-count="$store.state.pages"
layout="prev, pager, next"
background
/>
GET_CHARACTERS
? Не вижу. Надо добавить.let data = await axios.get(baseURL); context.commit('SET_CHARACTERS', data)
const response = await axios.get(baseURL);
context.commit('SET_CHARACTERS', response.data.results);
<div>{{ $store.state.characters }}</div>
<div v-for="n in $store.state.characters">
{{ n.name }}
</div>
В App.vue я запрашиваю все продукты из БД
store.dispatch('GET_PRODUCTS').then(() => {
new Vue({ ... });
});
watch: {
'$store.state.products': {
immediate: true,
handler(products) {
if (products) {
// можно что-то сделать
}
},
},
},
const find = (arr, id) =>
(Array.isArray(arr) ? arr : []).reduce((found, n) =>
found || (n.id === id ? n : find(n.replies, id))
, null);
// Вот так не работает почему-то: // this.GET_HERITAGEOBJECTS_FROM_DB()
this.dispatch('GET_HERITAGEOBJECTS_FROM_DB');
// Vue ругается: error Unreachable code no-unreachable
Error: [vuex] do not mutate vuex store state outside mutation handlers.
this.$store.commit('vehicles/addVehicle', { ...this.vehicle });
// или
addVehicle: (state, payload) => state.vehicles.push({ ...payload }),
methods: {
createNewVehicle: () => ({
name: '',
description: '',
rent: '',
type: 'custom',
}),
...
data() {
return {
vehicle: this.createNewVehicle(),
};
},
this.$store.commit('vehicles/addVehicle', this.vehicle);
this.vehicle = this.createNewVehicle();
state: {
page: 0,
perPage: 5,
total: 0,
posts: [],
loading: false,
},
getters: {
numPages: state => Math.ceil(state.total / state.perPage),
},
mutations: {
updateLoading: (state, loading) => state.loading = loading,
updatePosts: (state, { posts, total, page }) => Object.assign(state, { posts, total, page }),
},
actions: {
async fetchPosts({ state, commit }, page) {
commit('updateLoading', true);
const start = (page - 1) * state.perPage;
const end = page * state.perPage;
const url = `https://jsonplaceholder.typicode.com/posts?_start=${start}&_end=${end}`;
try {
const response = await fetch(url);
const posts = await response.json();
const total = response.headers.get('x-total-count');
commit('updatePosts', { posts, total, page });
} catch (e) {
console.error(e);
}
commit('updateLoading', false);
},
},
props: [ 'page', 'numPages' ],
methods: {
goTo(page) {
this.$emit('paginate', page);
},
next(step) {
this.goTo(this.page + step);
},
},
computed: {
isFirst() {
return this.page <= 1;
},
isLast() {
return this.page >= this.numPages;
},
},
<button @click="goTo(1)" :disabled="isFirst"><<</button>
<button @click="next(-1)" :disabled="isFirst"><</button>
{{ page }} / {{ numPages }}
<button @click="next(+1)" :disabled="isLast">></button>
<button @click="goTo(numPages)" :disabled="isLast">>></button>
v-model
:model: {
prop: 'page',
event: 'paginate',
},
computed: {
page: {
get() {
return this.$store.state.page;
},
set(page) {
this.$store.dispatch('fetchPosts', page);
},
},
<компонент-пагинации
v-model="page"
:num-pages="$store.getters.numPages"
/>
created() {
this.page = 1;
},
<div v-if="$store.state.loading">данные загружаются, ждите</div>
<компонент-для-отображения-данных v-else :данные="$store.state.posts" />
getters: {
postsByCatId: ({ posts }) =>
posts.reduce((acc, n) => (
(acc[n.catId] = acc[n.catId] || []).push(n),
acc
), {}),
},
const postsMixin = {
data: () => ({
catId: null,
}),
computed: {
posts() {
return this.$store.getters.postsByCatId[this.catId] || [];
},
},
};
response
следует передавать response.data
mutations: {
setTodos: (state, todos) => state.todos = todos,
},
actions: {
async getTodos({ commit }) {
const results = [];
for (let i = 1; i <= 10; i++) {
try {
const { data } = await axios.get(`https://jsonplaceholder.typicode.com/todos/${i}`);
results.push(data);
} catch (e) {
console.log(e);
}
}
commit('setTodos', results);
},
},
<ul>
<li v-for="n in $store.state.todos" :key="n.id">
<div>#{{ n.id }}</div>
<div>{{ n.title }}</div>
</li>
</ul>
new Vue({
store: store,
...
new Vue({
store: createStore(),
...
state: {
opened: null,
...
<Trigger :block="block">
props: [ 'block' ],
computed: mapState([ 'opened' ]),
:class="{ 'active' : block === opened }"
@click="toggleNav(block)"
toggleNav(state, block) {
state.opened = state.opened === block ? null : block;
},
state.opened = block
(название мутации в этом случае конечно следует поменять).closeSidebarPanel(state) {
state.opened = null;
},
isPanelOpen(state) {
return !!state.opened;
},
<span v-if="isPanelOpen">{{ $store.state.opened.bName }}</span>
<slot :block="$store.state.opened"></slot>
<template #default="{ block }">
<div class="sidebar-panel-settings">
<div class="setting-block">
{{ block.bName }}
</div>
</div>
</template>
state: {
date: null,
interval: null,
},
mutations: {
update(state) {
state.date = new Date();
},
start(state) {
if (!state.interval) {
state.interval = setInterval(this.commit, 1000, 'update');
}
},
stop(state) {
if (state.interval) {
clearInterval(state.interval);
state.interval = null;
}
},
},
computed: {
timerActive() {
return !!this.$store.state.interval;
},
timeStr() {
const { date } = this.$store.state;
return date instanceof Date
? [ 'getHours', 'getMinutes', 'getSeconds' ]
.map(n => `${date[n]()}`.padStart(2, 0))
.join(':')
: 'ВРЕМЕНИ НЕТ';
},
},
created() {
this.$store.commit('start');
},
<button @click="$store.commit('start')" :disabled="timerActive">start</button>
<button @click="$store.commit('stop')" :disabled="!timerActive">stop</button>
<div>{{ timeStr }}</div>
state: {
wishlistIds: [],
...
plugins: [
createPersistedState({
paths: [ 'wishlistIds' ],
}),
...
getters: {
wishlist: state => state.games.filter(n => state.wishlistIds.includes(n.id)),
...
mutations: {
addGame(state, gameId) {
if (!state.wishlistIds.includes(gameId)) {
state.wishlistIds.push(gameId);
}
},
removeGame(state, gameId) {
const index = state.wishlistIds.indexOf(gameId);
if (index !== -1) {
state.wishlistIds.splice(index, 1);
}
},
...
computed: {
liked: {
get() {
return this.$store.state.wishlistIds.includes(this.game.id);
},
set(val) {
this.$store.commit(val ? 'addGame' : 'removeGame', this.game.id);
},
},
...
<button @click="liked = !liked" :class="{ liked }" class="like"></button>