CodeOrc.com - Learn by example
X
Make an RPG
Vue Implementations

Example of How to Implement an item shop in Vue

Here is an example of an item shop. There's one component for the log. And another component for the items for sale. We'll be going into more details on the communication between all these components in other sections. This section demonstrates how you can use multiple components to build an app.

Vue.component('bought-log', { props: ['entry_row'], template: `<tr> <td>{{ entry_row.name }}</td> <td>{{ entry_row.price}}</td> <td>{{ entry_row.id}}</td> </tr>` }); Vue.component('item-for-sale', { props: ['todo'], template: `<tr> <td>{{ todo.name }}</td> <td>{{ todo.price }}</td> <td> <input type='button' value='BUY' @click='buy(todo)'></input> </td> </tr>`, methods: { buy: function( todo ) { store.buying('buying', todo ); } } }); var store = new Vue({ el: '#store', data: { my_gold: 200, items_for_sale: [ { name: 'Staff', price: '15', currency: 'silver'}, { name: 'Sword', price: '35', currency: 'silver'}, { name: 'Potion', price: '25', currency: 'silver'} ], things_bought: [], next_id: 0 }, methods: { buying: function( text, todo ) { var str = 'Bought '+todo.name+ ' for '+ todo.price; this.my_gold -= todo.price; var log_entry = Vue.util.extend({}, todo); log_entry.id = this.next_id++; this.things_bought.push( log_entry ); } } });
DO IT

When you click on the buy button, the buy function get's called with the todo prop that was sent down as an argument:

@click='buy(todo)'

This passes the todo object that was rendered up to the buy function. The buy function is initially called on it's own component, but then we use that function to call the main store:

buy: function( todo ) { store.buying('buying', todo ); }

The main store contains all the logic needed to handle the buy request

methods: { buying: function( text, todo ) { var str = 'Bought '+todo.name+ ' for '+ todo.price; this.my_gold -= todo.price; var log_entry = Vue.util.extend({}, todo); log_entry.id = this.next_id++; this.things_bought.push( log_entry ); } }

We didn't want to affect the original todo item, so we clone it here:

var log_entry = Vue.util.extend({}, todo);

v-for can be tricky to think about.

<bought-log v-for="entry in things_bought" v-bind:entry_row="entry" v-bind:key="entry.id"> </bought-log>

Consider the tag and the attribute contents within the tags to be occuring in the parent instance scope. Hence things_bought is a data attribute of the store.

Think of the v-binds:xxx to be the things you're passing down. Hence, entry_row is a prop inside the bought-log.

In the next lesson, we will learn about How to Create a Tree View in Vue

Get the Latest Tutorial Updates
<< >>
X