Vue 2, Vuex & Vue-router
by schantanu
HTML
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<script src="https://unpkg.com/vuex/dist/vuex.js"></script>
<script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
<div id="app">
<router-view></router-view>
</div>
SCSS
* {
box-sizing: border-box;
}
.listing {
list-style-type: none;
overflow: hidden;
padding: 0;
li {
float: left;
width: 175px;
padding: 10px;
text-align: center;
border: 1px #ddd solid;
background: white;
margin: 5px;
cursor: pointer;
img {
width: 100%;
margin-bottom: 7px;
}
&:hover {
background: #eee;
}
}
}
.item-view {
text-align: center;
}
.item {
background: white;
padding: 10px;
}
a {
font-size: 16px;
display: inline-block;
padding: 10px;
border: 1px #ddd solid;
background: white;
color: black;
margin: 10px;
&.back-listing {
position: absolute;
left: 0;
top: 0;
}
}
Babel + JSX
const ListingView = {
template: `
<ul class="listing">
<li v-for="item in $store.state.items" @click="viewItem(item)">
<br>{{ item.name }}
</li>
</ul>
`,
methods: {
viewItem: function (item) {
this.$router.push({ name: 'item', params: { id: item.id } })
}
}
}
const ItemView = {
template: `<div class="item-view">
<router-link class="back-listing" :to="{name: 'listing'}">Back to listing</router-link>
<div class="item">
<h1>{{ item.name }}</h1>
<p>{{ item.price }}</p>
<img :src="item.image" />
</div>
</div>`,
computed: {
item: function () {
return this.$store.state.items.find((item) => {
return item.id === this.$route.params.id
})
}
}
}
const store = new Vuex.Store({
state: {
items: [{
id: 'a',
name: 'Item #1',
price: '$10',
image: 'http://lorempicsum.com/simpsons/350/200/1'
}, {
id: 'b',
name: 'Item #2',
price: '$20',
image: 'http://lorempicsum.com/simpsons/350/200/2'
}, {
id: 'c',
name: 'Item #3',
price: '$30',
image: 'http://lorempicsum.com/simpsons/350/200/3'
}]
}
})
const router = new VueRouter({
routes: [
{ name: 'listing', path: '/', component: ListingView },
{ name: 'item', path: '/item/:id', component: ItemView }
]
})
new Vue({
el: '#app',
store,
router
})