vue.md 8.27 KB
Newer Older
Filipa Lacerda's avatar
Filipa Lacerda committed
1 2 3 4
# Vue

To get started with Vue, read through [their documentation][vue-docs].

5
## Examples
Filipa Lacerda's avatar
Filipa Lacerda committed
6

7
What is described in the following sections can be found in these examples:
8

9 10 11
- web ide: <https://gitlab.com/gitlab-org/gitlab-ce/tree/master/app/assets/javascripts/ide/stores>
- security products: <https://gitlab.com/gitlab-org/gitlab-ee/tree/master/ee/app/assets/javascripts/vue_shared/security_reports>
- registry: <https://gitlab.com/gitlab-org/gitlab-ce/tree/master/app/assets/javascripts/registry/stores>
12

13
## Vue architecture
14

15 16 17
All new features built with Vue.js must follow a [Flux architecture][flux].
The main goal we are trying to achieve is to have only one data flow and only one data entry.
In order to achieve this goal we use [vuex](#vuex).
18 19 20 21

You can also read about this architecture in vue docs about [state management][state-management]
and about [one way data flow][one-way-data-flow].

22
### Components and Store
Filipa Lacerda's avatar
Filipa Lacerda committed
23 24 25 26 27 28 29 30

In some features implemented with Vue.js, like the [issue board][issue-boards]
or [environments table][environments-table]
you can find a clear separation of concerns:

```
new_feature
├── components
31
│   └── component.vue
Filipa Lacerda's avatar
Filipa Lacerda committed
32
│   └── ...
33
├── store
34
│  └── new_feature_store.js
35
├── index.js
Filipa Lacerda's avatar
Filipa Lacerda committed
36 37 38 39 40
```
_For consistency purposes, we recommend you to follow the same structure._

Let's look into each of them:

41
### A `index.js` file
Filipa Lacerda's avatar
Filipa Lacerda committed
42 43 44 45

This is the index file of your new feature. This is where the root Vue instance
of the new feature should be.

46 47
The Store and the Service should be imported and initialized in this file and
provided as a prop to the main component.
Filipa Lacerda's avatar
Filipa Lacerda committed
48

49
Don't forget to follow [these steps][page_specific_javascript].
Filipa Lacerda's avatar
Filipa Lacerda committed
50

51
### Bootstrapping Gotchas
52
#### Providing data from HAML to JavaScript
53 54 55
While mounting a Vue application may be a need to provide data from Rails to JavaScript.
To do that, provide the data through `data` attributes in the HTML element and query them while mounting the application.

56
_Note:_ You should only do this while initializing the application, because the mounted element will be replaced with Vue-generated DOM.
57 58 59 60 61 62 63 64 65

The advantage of providing data from the DOM to the Vue instance through `props` in the `render` function
instead of querying the DOM inside the main vue component is that makes tests easier by avoiding the need to
create a fixture or an HTML element in the unit test. See the following example:

```javascript
// haml
.js-vue-app{ data: { endpoint: 'foo' }}

66
// index.js
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
document.addEventListener('DOMContentLoaded', () => new Vue({
  el: '.js-vue-app',
  data() {
    const dataset = this.$options.el.dataset;
    return {
      endpoint: dataset.endpoint,
    };
  },
  render(createElement) {
    return createElement('my-component', {
      props: {
        endpoint: this.isLoading,
      },
    });
  },
}));
```

#### Accessing the `gl` object
86
When we need to query the `gl` object for data that won't change during the application's life cyle, we should do it in the same place where we query the DOM.
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102
By following this practice, we can avoid the need to mock the `gl` object, which will make tests easier.
It should be done while initializing our Vue instance, and the data should be provided as `props` to the main component:

```javascript
document.addEventListener('DOMContentLoaded', () => new Vue({
  el: '.js-vue-app',
  render(createElement) {
    return createElement('my-component', {
      props: {
        username: gon.current_username,
      },
    });
  },
}));
```

103
### A folder for Components
Filipa Lacerda's avatar
Filipa Lacerda committed
104 105 106 107 108 109 110 111 112 113 114 115 116 117

This folder holds all components that are specific of this new feature.
If you need to use or create a component that will probably be used somewhere
else, please refer to `vue_shared/components`.

A good thumb rule to know when you should create a component is to think if
it will be reusable elsewhere.

For example, tables are used in a quite amount of places across GitLab, a table
would be a good fit for a component. On the other hand, a table cell used only
in one table would not be a good use of this pattern.

You can read more about components in Vue.js site, [Component System][component-system]

118
### A folder for the Store
Filipa Lacerda's avatar
Filipa Lacerda committed
119

120 121 122
#### Vuex
Check this [page](vuex.md) for more details.

Filipa Lacerda's avatar
Filipa Lacerda committed
123 124
## Style guide

125
Please refer to the Vue section of our [style guide](style_guide_js.md#vue-js)
Filipa Lacerda's avatar
Filipa Lacerda committed
126 127
for best practices while writing your Vue components and templates.

128 129 130 131 132 133 134
## Testing Vue Components

Each Vue component has a unique output. This output is always present in the render function.

Although we can test each method of a Vue component individually, our goal must be to test the output
of the render/template function, which represents the state at all times.

135
Make use of the [axios mock adapter](axios.md#mock-axios-response-on-tests) to mock data returned.
136 137 138 139

Here's how we would test the Todo App above:

```javascript
140 141 142
import Vue from 'vue';
import axios from '~/lib/utils/axios_utils';
import MockAdapter from 'axios-mock-adapter';
143 144

describe('Todos App', () => {
145 146 147 148 149 150 151
  let vm;
  let mock;

  beforeEach(() => {
    // Create a mock adapter for stubbing axios API requests
    mock = new MockAdapter(axios);

152 153
    const Component = Vue.extend(component);

154 155 156 157 158 159 160 161 162 163
    // Mount the Component
    vm = new Component().$mount();
  });

  afterEach(() => {
    // Reset the mock adapter
    mock.restore();
    // Destroy the mounted component
    vm.$destroy();
  });
164

165
  it('should render the loading state while the request is being made', () => {
166 167 168
    expect(vm.$el.querySelector('i.fa-spin')).toBeDefined();
  });

169 170 171 172
  it('should render todos returned by the endpoint', done => {
    // Mock the get request on the API endpoint to return data
    mock.onGet('/todos').replyOnce(200, [
      {
173
        title: 'This is a todo',
174 175 176
        text: 'This is the text',
      },
    ]);
177

178 179 180 181 182
    Vue.nextTick(() => {
      const items = vm.$el.querySelectorAll('.js-todo-list div')
      expect(items.length).toBe(1);
      expect(items[0].textContent).toContain('This is the text');
      done();
183
    });
184
  });
185

186
  it('should add a todos on button click', (done) => {
187

188 189 190 191
    // Mock the put request and check that the sent data object is correct
    mock.onPut('/todos').replyOnce((req) => {
      expect(req.data).toContain('text');
      expect(req.data).toContain('title');
192

193
      return [201, {}];
194 195
    });

196
    vm.$el.querySelector('.js-add-todo').click();
197

198 199 200 201
    // Add a new interceptor to mock the add Todo request
    Vue.nextTick(() => {
      expect(vm.$el.querySelectorAll('.js-todo-list div').length).toBe(2);
      done();
202 203 204 205
    });
  });
});
```
206 207

### `mountComponent` helper
Ville Skyttä's avatar
Ville Skyttä committed
208
There is a helper in `spec/javascripts/helpers/vue_mount_component_helper.js` that allows you to mount a component with the given props:
209 210 211

```javascript
import Vue from 'vue';
212
import mountComponent from 'spec/helpers/vue_mount_component_helper'
213 214 215 216 217 218 219
import component from 'component.vue'

const Component = Vue.extend(component);
const data = {prop: 'foo'};
const vm = mountComponent(Component, data);
```

220
### Test the component's output
221 222 223
The main return value of a Vue component is the rendered output. In order to test the component we
need to test the rendered output. [Vue][vue-test] guide's to unit test show us exactly that:

Filipa Lacerda's avatar
Filipa Lacerda committed
224
## Vue.js Expert Role
Filipa Lacerda's avatar
Filipa Lacerda committed
225
One should apply to be a Vue.js expert by opening an MR when the Merge Request's they create and review show:
Filipa Lacerda's avatar
Filipa Lacerda committed
226 227
- Deep understanding of Vue and Vuex reactivy
- Vue and Vuex code are structured according to both official and our guidelines
Filipa Lacerda's avatar
Filipa Lacerda committed
228
- Full understanding of testing a Vue and Vuex application
Filipa Lacerda's avatar
Filipa Lacerda committed
229
- Vuex code follows the [documented pattern](./vuex.md#actions-pattern-request-and-receive-namespaces)
Filipa Lacerda's avatar
Filipa Lacerda committed
230
- Knowledge about the existing Vue and Vuex applications and existing reusable components
Filipa Lacerda's avatar
Filipa Lacerda committed
231

Filipa Lacerda's avatar
Filipa Lacerda committed
232 233 234 235 236 237 238

[vue-docs]: http://vuejs.org/guide/index.html
[issue-boards]: https://gitlab.com/gitlab-org/gitlab-ce/tree/master/app/assets/javascripts/boards
[environments-table]: https://gitlab.com/gitlab-org/gitlab-ce/tree/master/app/assets/javascripts/environments
[page_specific_javascript]: https://docs.gitlab.com/ce/development/frontend.html#page-specific-javascript
[component-system]: https://vuejs.org/v2/guide/#Composing-with-Components
[state-management]: https://vuejs.org/v2/guide/state-management.html#Simple-State-Management-from-Scratch
239
[one-way-data-flow]: https://vuejs.org/v2/guide/components.html#One-Way-Data-Flow
240
[vue-test]: https://vuejs.org/v2/guide/unit-testing.html
241
[flux]: https://facebook.github.io/flux
242
[axios]: https://github.com/axios/axios