vueschool.io
Teacher @ Vue SchoolΒ
Full Stack developer
Consultant
Foodie πΆ
Oslo, Norway
Teacher @ Vue School
Author of The Majesty of Vue.jsΒ 1 & 2
Vue.js Contributor
Consultant @ BuildingLink
Amsterdam
Ensures a one way data flow
Action
Dispatcher
Store
View
Example
Action
Dispatcher
Store
View
User clicks add to cart in view
Action organize data
Dispatches to the Store
View reads from the Store
Action
Dispatcher
Store
View
Works like an event bus/hub in many ways
We do not have to "guide" events through components anymore
React β Redux
Vue β Vuex
The store is the global component that holds our data - the application state
export default {
data() {
return {
products: [...]
}
}
}
import Vuex from 'vuex'
export default new Vuex.Store({
state: {
products: [...]
}
})
The store is the "component"
The state is the "data"
Vuex solves certain problems, but you should not store everything
Yes β Vuex Store
No β Components data
npm install vuex --save
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// store.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export new Vuex.Store({
state: {
// Top 3 movies of all time according to IMDB
movies: [
{id: 1, name: 'The Shawshank Redemption'},
{id: 2, name: 'The Dark Knight'},
{id: 3, name: 'The Godfather'}
]
}
})
import store from '@/store'
// main.js
import Vue from 'vue'
import store from '@/store'
import router from '@/router'
import App from '@/App'
new Vue({
store,
router,
el: '#app',
components: {
App
},
template: '<App/>'
})
// MoviesList.vue
export default {
computed: {
movies () {
return this.$store.state.movies
}
}
}