Skip to content

Vue Smart Table in 5 Minutes

Andrea edited this page Jun 12, 2016 · 16 revisions

Let's say you want to consume a complicated json http://api.randomuser.me/?page=1&results=20&seed=a but you don't have much time.

First, you'd like two things, for Smart Table to gather the data from that endpoint (endpoint) and to do it on start (auto-load), you'd write:

<smart-table :auto-load="true" endpoint="http://api.randomuser.me/?page=1&results=20"></smart-table>

If you do this, you'll get an empty page because Smart Table by default looks for the json path body which is not present in our json. Instead we have the property results. Let's modify our code:

<smart-table :auto-load="true" endpoint="http://api.randomuser.me/?page=1&results=20" body-field="results">
</smart-table>

After that we get this:

Way too many columns, and some are not even displaying. Let's say we only want the name and a picture.

We need to edit the header prop to this:

<smart-table
  :auto-load="true"
  endpoint="http://api.randomuser.me/?page=1&results=20"
  body-field="results"
  :header="{'name.first': 'Name', 'picture.thumbnail': 'Avatar'}"
></smart-table>

We can use the dot notation to navigate the data and print the right columns. Also, we would like the picture to render directly in the page, not a lousy link.

We need to write a component to do that. Don't worry it will take a minute.

Every component is just a vue component, it will be rendered inside each cell of a particular column. Smart Table will populate its value property with the actual cell data. We will call this component src2img:

Vue.component('src2img', {
  template: '<img :src="value"></img>',
  data () {
    return { value: '' }
  }
})

This will register the component globally, as you can see, it simply pass whatever value you give it to a <img> tag, really nothing fancy but it works!

To add it to our Smart Table we will just tell what in which column it should appear:

<smart-table
  :auto-load="true"
  endpoint="http://api.randomuser.me/?page=1&results=20"
  body-field="results"
  :header="{'name.first': 'Name', 'picture.thumbnail': 'Avatar'}"
>
  <src2img slot="picture.thumbnail"></src2img>
</smart-table>

And that is really it.

Bonus part!

If you want to order by name, you will have to tell this explicitly to the table:

<smart-table
  :auto-load="true"
  endpoint="http://api.randomuser.me/?page=1&results=20"
  body-field="results"
  :header="{'name.first': 'Name', 'picture.thumbnail': 'Avatar'}"
  :order-by="['name.first']"
>
  <src2img slot="picture.thumbnail"></src2img>
</smart-table>

Clicking on the column title will order the table.

Clone this wiki locally