Open yuyuyuriko78 opened 4 years ago
npm install vuex --save
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
import Vue from 'vue'
import App from './App.vue'
import store from './srore'
new Vue({
store,
render: h => h(App),
}).mount('#app')
import Vue from 'vue';
import Vuex from 'vuex';
import データ from 'フォルダ';
Vue.use(Vuex);
const store = new Vuex.Store({
state: {},
getters: {},
mutations: {},
actions: {},
});
名前 | 役割 | 補足 |
---|---|---|
state | データそのもの | aa |
getters | stateのデータをVueコンポーネントに渡す | aaa |
mutations | stateのデータを変更することができる唯一の存在 | コミットにより呼び出す |
actions | APIと非同期通信を行い取得したデータをコミットする | mutationsを呼び出す |
import Vue from 'vue';
import Vuex from 'vuex';
import books from './books';
Vue.use(Vuex);
const store = new Vuex.Store({ state: { books, }, getters: { getNewBookId(state) { return state.books.length + 1; }, findBookById: (state) => (id) => { return state.books.find((book) => book.id === id); }, }, mutations: { saveNewBook: function(state, book){ state.books.push(book); }, updateBook: function(state, { oldBook, newBook }){ Object.assign(oldBook, newBook); }, }, actions: { addBook: function({ commit, getters}, book){ commit('saveNewBook', { id: getters.getNewBookId, ...book, }); }, updateBook: function({ commit, getters }, {id, book} ){ const oldBook = getters.findBookById(id); if(oldBook) { commit('updateBook', {oldBook, newBook: book}); } } }, });
export default store;
book.js
```js
const books = [
{
id: 1,
title: 'JS Book',
author: 'Suzuki',
image: require('@/assets/web.png'),
isFavorite: true,
},
{
id: 2,
title: 'PHP Book',
author: 'Tanaka',
image: require('@/assets/programming.png'),
isFavorite: false,
},
];
export default books;
NewBook.vue(コンポーネント)
<script>
import BookForm from '@/components/BookForm';
export default {
name: 'NewBook',
components: { BookForm },
methods: {
onSubmit(book) {
this.$store.dispatch('addBook', book);
this.$router.push('/');
},
},
};
</script>
store.js
actions: {
addBook: function({ commit, getters }, book){
commit('saveNewBook', {
id: getters.getNewBookId,
...book,
});
},
},
store.js
mutations: {
saveNewBook: function(state, book){
state.books.push(book);
},
},
Top.vue(コンポーネント)
computed: {
books() {
return this.$store.state.books;
}
}
store.js
getters: {
todos(state) {
return state.books.author
}
}
Sample.vue(コンポーネント)
computed: {
todos() {
this.$store.getters.todos
}
}
store.js
getters: {
squared: function(state) {
return state.count * state.count
},
}
Sample2.js
computed: {
square() {
this.$store.getters.squared
}
}
Vuex