user Created with Sketch.
Group 2 Created with Sketch.

Vue - Introduktion

1. Quick-start

  1. Copy one of the example components under: /js/vue/components.
  2. Load the javascript-file in standard.html (before vue_wrapper.js).
  3. Hear me, and rejoice!

2. When to use Vue

It's quite simple, if you can achieve your goal using Twig and regular HTML, do that. If you need something to be "reactive" to changes without reloading the entire page, use Vue.

Example use cases:
  • Toggles
  • AJAX-submits
Important note: Do not use Vue for anything that needs to be indexed by search engines. There are ways to make this work, but we'll cross the bridge when we get there.

3. Directories and files


/standard.html

Every new component must be included here, before vue_wrapper.js.
To enable developer tools and debugging, super admins have access to the development version.


/js/vue/vue_wrapper.js

Since Vue isn't the only sheriff in town (looking at you jQuery) we might run into unforeseen consequences if we wrap the entire page in a single large Vue instance. What we do instead is to compartmentalize each component within its own Vue instance. That's what vue_wrapper.js does.

It also listens for a few global JS-events that tells us that the page might have been altered and initializes any new instances.

You shouldn't have to touch this one.


 

/js/vue/components

Each component has its own directory, usually containing 2 files:

Exempelbild

 

component.js

Besides the usual Vue magic, this file is responsible for registering the component with Vue so it can be accessed.

(function () {
  window.Vue.component('example-list', {
    data: function () {
      return {
        names: "The Debugger"
      };
    }
  });
})();

template.html

In the example components, this file includes a Twig macro to which Twig variables that should be available to the component are passed. This is not required, but recommended.

You can edit almost everything in this file, though if you remove some of the following, things might not work as intended.. or at all:

  • data-vue-wrapper - Required by vue_wrapper.js.
  • inline-template - Without this we cannot place any of the template code here.
  • v-cloak - Hides the component until everything is loaded.
{% macro print(list, name) %}
  <div data-vue-wrapper>
      <example-list inline-template v-cloak>
      <div>
        <h1>{{ '{{ name }}' }}</h1>
        <h1>{% verbatim %}{{ name }}{% endverbatim %}</h1>
      </div>
    </example-list>
  </div>
{% endmacro %}

4. Tips and gotchas

Every component must have a single root element, that's why some components contain a single wrapping div.

4.1 Further reading

https://vuejs.org/
https://vuejs.org/v2/guide/
https://laracasts.com/series/learn-vue-2-step-by-step
https://vuejs-tips.github.io/cheatsheet/