2021-01-29 00:20:46 +05:30
---
stage: none
group: unassigned
2021-02-22 17:27:13 +05:30
info: To determine the technical writer assigned to the Stage/Group associated with this page, see https://about.gitlab.com/handbook/engineering/ux/technical-writing/#assignments
2021-01-29 00:20:46 +05:30
---
2017-08-17 22:00:37 +05:30
# Vue
2019-12-21 20:55:43 +05:30
To get started with Vue, read through [their documentation ](https://vuejs.org/v2/guide/ ).
2017-08-17 22:00:37 +05:30
2018-11-18 11:00:15 +05:30
## Examples
2017-08-17 22:00:37 +05:30
2018-11-18 11:00:15 +05:30
What is described in the following sections can be found in these examples:
2018-03-17 18:26:18 +05:30
2020-06-23 00:09:42 +05:30
- [Web IDE ](https://gitlab.com/gitlab-org/gitlab-foss/tree/master/app/assets/javascripts/ide/stores )
- [Security products ](https://gitlab.com/gitlab-org/gitlab/tree/master/ee/app/assets/javascripts/vue_shared/security_reports )
- [Registry ](https://gitlab.com/gitlab-org/gitlab-foss/tree/master/app/assets/javascripts/registry/stores )
2017-08-17 22:00:37 +05:30
2018-11-18 11:00:15 +05:30
## Vue architecture
2017-08-17 22:00:37 +05:30
2020-05-24 23:13:21 +05:30
All new features built with Vue.js must follow a [Flux architecture ](https://facebook.github.io/flux/ ).
2018-11-18 11:00:15 +05:30
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 ).
2017-08-17 22:00:37 +05:30
2020-06-23 00:09:42 +05:30
You can also read about this architecture in Vue docs about [state management ](https://vuejs.org/v2/guide/state-management.html#Simple-State-Management-from-Scratch )
2020-05-24 23:13:21 +05:30
and about [one way data flow ](https://vuejs.org/v2/guide/components.html#One-Way-Data-Flow ).
2017-08-17 22:00:37 +05:30
2018-11-18 11:00:15 +05:30
### Components and Store
2017-08-17 22:00:37 +05:30
2020-05-24 23:13:21 +05:30
In some features implemented with Vue.js, like the [issue board ](https://gitlab.com/gitlab-org/gitlab-foss/tree/master/app/assets/javascripts/boards )
or [environments table ](https://gitlab.com/gitlab-org/gitlab-foss/tree/master/app/assets/javascripts/environments )
2017-08-17 22:00:37 +05:30
you can find a clear separation of concerns:
2020-04-22 19:07:51 +05:30
```plaintext
2017-08-17 22:00:37 +05:30
new_feature
├── components
2018-05-09 12:01:36 +05:30
│ └── component.vue
2017-08-17 22:00:37 +05:30
│ └── ...
2018-11-18 11:00:15 +05:30
├── store
2018-05-09 12:01:36 +05:30
│ └── new_feature_store.js
2018-10-15 14:42:47 +05:30
├── index.js
2017-08-17 22:00:37 +05:30
```
2019-09-30 21:07:59 +05:30
2017-08-17 22:00:37 +05:30
_For consistency purposes, we recommend you to follow the same structure._
Let's look into each of them:
2019-07-31 22:56:46 +05:30
### An `index.js` file
2017-08-17 22:00:37 +05:30
This is the index file of your new feature. This is where the root Vue instance
of the new feature should be.
The Store and the Service should be imported and initialized in this file and
provided as a prop to the main component.
2021-01-29 00:20:46 +05:30
Be sure to read about [page-specific JavaScript ](performance.md#page-specific-javascript ).
2017-08-17 22:00:37 +05:30
2018-03-17 18:26:18 +05:30
### Bootstrapping Gotchas
2019-09-30 21:07:59 +05:30
2018-11-08 19:23:39 +05:30
#### Providing data from HAML to JavaScript
2019-09-30 21:07:59 +05:30
2020-07-28 23:09:34 +05:30
While mounting a Vue application, you might need to provide data from Rails to JavaScript.
To do that, you can use the `data` attributes in the HTML element and query them while mounting the application.
2018-03-17 18:26:18 +05:30
2021-02-22 17:27:13 +05:30
You should only do this while initializing the application, because the mounted element is replaced with a Vue-generated DOM.
2018-03-17 18:26:18 +05:30
The advantage of providing data from the DOM to the Vue instance through `props` in the `render` function
2020-07-28 23:09:34 +05:30
instead of querying the DOM inside the main Vue component is avoiding the need to create a fixture or an HTML element in the unit test,
2021-02-22 17:27:13 +05:30
which makes the tests easier.
2021-01-29 00:20:46 +05:30
See the following example, also, please refer to our [Vue style guide ](style/vue.md#basic-rules ) for additional
information on why we explicitly declare the data being passed into the Vue app;
2018-03-17 18:26:18 +05:30
```javascript
// haml
2020-10-24 23:57:45 +05:30
#js-vue-app{ data: { endpoint: 'foo' }}
2018-03-17 18:26:18 +05:30
2018-11-08 19:23:39 +05:30
// index.js
2021-01-29 00:20:46 +05:30
const el = document.getElementById('js-vue-app');
if (!el) return false;
const { endpoint } = el.dataset;
return new Vue({
el,
2018-03-17 18:26:18 +05:30
render(createElement) {
return createElement('my-component', {
props: {
2021-01-29 00:20:46 +05:30
endpoint
2018-03-17 18:26:18 +05:30
},
});
},
2021-02-22 17:27:13 +05:30
});
2018-03-17 18:26:18 +05:30
```
2020-10-24 23:57:45 +05:30
> When adding an `id` attribute to mount a Vue application, please make sure this `id` is unique across the codebase
2018-03-17 18:26:18 +05:30
#### Accessing the `gl` object
2019-09-30 21:07:59 +05:30
2021-02-22 17:27:13 +05:30
When we need to query the `gl` object for data that doesn't change during the application's life cycle, we should do it in the same place where we query the DOM.
By following this practice, we can avoid the need to mock the `gl` object, which makes tests easier.
2018-03-17 18:26:18 +05:30
It should be done while initializing our Vue instance, and the data should be provided as `props` to the main component:
```javascript
2021-01-29 00:20:46 +05:30
return new Vue({
2018-03-17 18:26:18 +05:30
el: '.js-vue-app',
render(createElement) {
return createElement('my-component', {
props: {
username: gon.current_username,
},
});
},
2021-01-29 00:20:46 +05:30
});
2018-03-17 18:26:18 +05:30
```
2019-12-21 20:55:43 +05:30
#### Accessing feature flags
Use Vue's [provide/inject ](https://vuejs.org/v2/api/#provide-inject ) mechanism
to make feature flags available to any descendant components in a Vue
application. The `glFeatures` object is already provided in `commons/vue.js` , so
2021-01-29 00:20:46 +05:30
only the mixin is required to use the flags:
2019-12-21 20:55:43 +05:30
```javascript
// An arbitrary descendant component
import glFeatureFlagsMixin from '~/vue_shared/mixins/gl_feature_flags_mixin';
export default {
// ...
mixins: [glFeatureFlagsMixin()],
// ...
created() {
if (this.glFeatures.myFlag) {
// ...
}
},
}
```
This approach has a few benefits:
- Arbitrarily deeply nested components can opt-in and access the flag without
intermediate components being aware of it (c.f. passing the flag down via
props).
- Good testability, since the flag can be provided to `mount` /`shallowMount`
2020-07-28 23:09:34 +05:30
from `vue-test-utils` simply as a prop.
2019-12-21 20:55:43 +05:30
```javascript
import { shallowMount } from '@vue/test-utils';
shallowMount(component, {
provide: {
glFeatures: { myFlag: true },
},
});
```
- No need to access a global variable, except in the application's
[entry point ](#accessing-the-gl-object ).
2017-08-17 22:00:37 +05:30
### A folder for Components
2021-02-22 17:27:13 +05:30
This folder holds all components that are specific to this new feature.
If you need to use or create a component that is likely to be used somewhere
2017-08-17 22:00:37 +05:30
else, please refer to `vue_shared/components` .
2020-07-28 23:09:34 +05:30
A good rule of thumb to know when you should create a component is to think if
2021-02-22 17:27:13 +05:30
it could be reusable elsewhere.
2017-08-17 22:00:37 +05:30
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.
2020-05-24 23:13:21 +05:30
You can read more about components in Vue.js site, [Component System ](https://vuejs.org/v2/guide/#Composing-with-Components ).
2017-08-17 22:00:37 +05:30
### A folder for the Store
2018-10-15 14:42:47 +05:30
#### Vuex
2019-09-30 21:07:59 +05:30
2018-10-15 14:42:47 +05:30
Check this [page ](vuex.md ) for more details.
2019-07-07 11:18:12 +05:30
### Mixing Vue and jQuery
- Mixing Vue and jQuery is not recommended.
2019-09-30 21:07:59 +05:30
- If you need to use a specific jQuery plugin in Vue, [create a wrapper around it ](https://vuejs.org/v2/examples/select2.html ).
2019-07-07 11:18:12 +05:30
- It is acceptable for Vue to listen to existing jQuery events using jQuery event listeners.
- It is not recommended to add new jQuery events for Vue to interact with jQuery.
2021-01-29 00:20:46 +05:30
### Mixing Vue and JavaScript classes (in the data function)
In the [Vue documentation ](https://vuejs.org/v2/api/#Options-Data ) the Data function/object is defined as follows:
2021-02-22 17:27:13 +05:30
> The data object for the Vue instance. Vue recursively converts its properties into getter/setters to make it “reactive”. The object must be plain: native objects such as browser API objects and prototype properties are ignored. A rule of thumb is that data should just be data - it is not recommended to observe objects with their own stateful behavior.
2021-01-29 00:20:46 +05:30
Based on the Vue guidance:
- **Do not** use or create a JavaScript class in your [data function ](https://vuejs.org/v2/api/#data ), such as `user: new User()` .
- **Do not** add new JavaScript class implementations.
- **Do** use [GraphQL ](../api_graphql_styleguide.md ), [Vuex ](vuex.md ) or a set of components if cannot use simple primitives or objects.
- **Do** maintain existing implementations using such approaches.
- **Do** Migrate components to a pure object model when there are substantial changes to it.
- **Do** add business logic to helpers or utils, so you can test them separately from your component.
#### Why
There are additional reasons why having a JavaScript class presents maintainability issues on a huge codebase:
- Once a class is created, it is easy to extend it in a way that can infringe Vue reactivity and best practices.
- A class adds a layer of abstraction, which makes the component API and its inner workings less clear.
- It makes it harder to test. Since the class is instantiated by the component data function, it is harder to 'manage' component and class separately.
- Adding OOP to a functional codebase adds yet another way of writing code, reducing consistency and clarity.
2017-08-17 22:00:37 +05:30
## Style guide
2020-01-01 13:55:28 +05:30
Please refer to the Vue section of our [style guide ](style/vue.md )
2021-01-29 00:20:46 +05:30
for best practices while writing and testing your Vue components and templates.
2017-08-17 22:00:37 +05:30
## Testing Vue Components
2021-01-29 00:20:46 +05:30
Please refer to the [Vue testing style guide ](style/vue.md#vue-testing )
for guidelines and best practices for testing your Vue components.
2017-08-17 22:00:37 +05:30
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.
2020-05-24 23:13:21 +05:30
Here's an example of a well structured unit test for [this Vue component ](#appendix---vue-component-subject-under-test ):
2017-08-17 22:00:37 +05:30
```javascript
2020-05-24 23:13:21 +05:30
import { shallowMount } from '@vue/test-utils';
import { GlLoadingIcon } from '@gitlab/ui';
2018-11-08 19:23:39 +05:30
import MockAdapter from 'axios-mock-adapter';
2020-05-24 23:13:21 +05:30
import axios from '~/lib/utils/axios_utils';
import App from '~/todos/app.vue';
const TEST_TODOS = [
{ text: 'Lorem ipsum test text' },
{ text: 'Lorem ipsum 2' },
];
const TEST_NEW_TODO = 'New todo title';
const TEST_TODO_PATH = '/todos';
2017-08-17 22:00:37 +05:30
2020-05-24 23:13:21 +05:30
describe('~/todos/app.vue', () => {
let wrapper;
2018-11-08 19:23:39 +05:30
let mock;
beforeEach(() => {
2020-05-24 23:13:21 +05:30
// IMPORTANT: Use axios-mock-adapter for stubbing axios API requests
2018-11-08 19:23:39 +05:30
mock = new MockAdapter(axios);
2020-05-24 23:13:21 +05:30
mock.onGet(TEST_TODO_PATH).reply(200, TEST_TODOS);
mock.onPost(TEST_TODO_PATH).reply(200);
2018-11-08 19:23:39 +05:30
});
afterEach(() => {
2020-05-24 23:13:21 +05:30
// IMPORTANT: Clean up the component instance and axios mock adapter
wrapper.destroy();
wrapper = null;
2017-08-17 22:00:37 +05:30
2020-05-24 23:13:21 +05:30
mock.restore();
2017-08-17 22:00:37 +05:30
});
2021-01-29 00:20:46 +05:30
// It is very helpful to separate setting up the component from
2020-05-24 23:13:21 +05:30
// its collaborators (i.e. Vuex, axios, etc.)
const createWrapper = (props = {}) => {
wrapper = shallowMount(App, {
propsData: {
path: TEST_TODO_PATH,
...props,
2018-11-08 19:23:39 +05:30
},
2020-05-24 23:13:21 +05:30
});
};
2021-01-29 00:20:46 +05:30
// Helper methods greatly help test maintainability and readability.
2020-05-24 23:13:21 +05:30
const findLoader = () => wrapper.find(GlLoadingIcon);
const findAddButton = () => wrapper.find('[data-testid="add-button"]');
const findTextInput = () => wrapper.find('[data-testid="text-input"]');
const findTodoData = () => wrapper.findAll('[data-testid="todo-item"]').wrappers.map(wrapper => ({ text: wrapper.text() }));
describe('when mounted and loading', () => {
beforeEach(() => {
// Create request which will never resolve
mock.onGet(TEST_TODO_PATH).reply(() => new Promise(() => {}));
createWrapper();
});
2017-08-17 22:00:37 +05:30
2020-05-24 23:13:21 +05:30
it('should render the loading state', () => {
expect(findLoader().exists()).toBe(true);
2017-08-17 22:00:37 +05:30
});
2018-11-08 19:23:39 +05:30
});
2017-08-17 22:00:37 +05:30
2020-05-24 23:13:21 +05:30
describe('when todos are loaded', () => {
beforeEach(() => {
createWrapper();
// IMPORTANT: This component fetches data asynchronously on mount, so let's wait for the Vue template to update
return wrapper.vm.$nextTick();
});
2017-08-17 22:00:37 +05:30
2020-05-24 23:13:21 +05:30
it('should not show loading', () => {
expect(findLoader().exists()).toBe(false);
});
2017-08-17 22:00:37 +05:30
2020-05-24 23:13:21 +05:30
it('should render todos', () => {
expect(findTodoData()).toEqual(TEST_TODOS);
2017-08-17 22:00:37 +05:30
});
2020-05-24 23:13:21 +05:30
it('when todo is added, should post new todo', () => {
findTextInput().vm.$emit('update', TEST_NEW_TODO)
findAddButton().vm.$emit('click');
2017-08-17 22:00:37 +05:30
2020-05-24 23:13:21 +05:30
return wrapper.vm.$nextTick()
.then(() => {
expect(mock.history.post.map(x => JSON.parse(x.data))).toEqual([{ text: TEST_NEW_TODO }]);
});
2017-08-17 22:00:37 +05:30
});
});
});
```
2018-11-08 19:23:39 +05:30
2020-05-24 23:13:21 +05:30
### Test the component's output
2019-09-30 21:07:59 +05:30
2020-05-24 23:13:21 +05:30
The main return value of a Vue component is the rendered output. In order to test the component we
2020-10-24 23:57:45 +05:30
need to test the rendered output. Visit the [Vue testing guide ](https://vuejs.org/v2/guide/testing.html#Unit-Testing ).
2020-05-24 23:13:21 +05:30
### Events
We should test for events emitted in response to an action within our component, this is useful to verify the correct events are being fired with the correct arguments.
For any DOM events we should use [`trigger` ](https://vue-test-utils.vuejs.org/api/wrapper/#trigger ) to fire out event.
2018-03-17 18:26:18 +05:30
```javascript
2020-05-24 23:13:21 +05:30
// Assuming SomeButton renders: < button > Some button< / button >
wrapper = mount(SomeButton);
2018-03-17 18:26:18 +05:30
2020-05-24 23:13:21 +05:30
...
it('should fire the click event', () => {
const btn = wrapper.find('button')
btn.trigger('click');
...
})
2018-03-17 18:26:18 +05:30
```
2020-05-24 23:13:21 +05:30
When we need to fire a Vue event, we should use [`emit` ](https://vuejs.org/v2/guide/components-custom-events.html ) to fire our event.
2019-09-30 21:07:59 +05:30
2020-05-24 23:13:21 +05:30
```javascript
wrapper = shallowMount(DropdownItem);
...
it('should fire the itemClicked event', () => {
DropdownItem.vm.$emit('itemClicked');
...
})
```
We should verify an event has been fired by asserting against the result of the [`emitted()` ](https://vue-test-utils.vuejs.org/api/wrapper/#emitted ) method
2017-08-17 22:00:37 +05:30
2019-02-15 15:39:39 +05:30
## Vue.js Expert Role
2019-09-30 21:07:59 +05:30
2020-07-28 23:09:34 +05:30
You should only apply to be a Vue.js expert when your own merge requests and your reviews show:
2019-07-07 11:18:12 +05:30
2020-01-01 13:55:28 +05:30
- Deep understanding of Vue and Vuex reactivity
2019-02-15 15:39:39 +05:30
- Vue and Vuex code are structured according to both official and our guidelines
- Full understanding of testing a Vue and Vuex application
2020-05-24 23:13:21 +05:30
- Vuex code follows the [documented pattern ](vuex.md#naming-pattern-request-and-receive-namespaces )
2019-02-15 15:39:39 +05:30
- Knowledge about the existing Vue and Vuex applications and existing reusable components
2020-05-24 23:13:21 +05:30
## Vue 2 -> Vue 3 Migration
> This section is added temporarily to support the efforts to migrate the codebase from Vue 2.x to Vue 3.x
Currently, we recommend to minimize adding certain features to the codebase to prevent increasing the tech debt for the eventual migration:
- filters;
- event buses;
- functional templated
- `slot` attributes
You can find more details on [Migration to Vue 3 ](vue3_migration.md )
## Appendix - Vue component subject under test
This is the template for the example component which is tested in the [Testing Vue components ](#testing-vue-components ) section:
```html
< template >
< div class = "content" >
< gl-loading-icon v-if = "isLoading" / >
< template v-else >
< div
v-for="todo in todos"
:key="todo.id"
:class="{ 'gl-strike': todo.isDone }"
data-testid="todo-item"
>{{ toddo.text }}< / div >
< footer class = "gl-border-t-1 gl-mt-3 gl-pt-3" >
< gl-form-input
type="text"
v-model="todoText"
data-testid="text-input"
>
< gl-button
variant="success"
data-testid="add-button"
@click ="addTodo"
>Add< / gl-button >
< / footer >
< / template >
< / div >
< / template >
```