├── .gitignore
├── README.md
└── images
├── DevTools.png
├── custom-directives.svg
├── flow.png
├── vuelifecycle.png
└── vuex-app-structure.png
/.gitignore:
--------------------------------------------------------------------------------
1 | # Cruft
2 | .DS_Store
3 | npm-debug.log
4 | .idea
5 | *.idea/
6 | .idea/workspace.xml
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Вопросы для собеседования VueJS разработчика
2 | Список из вопросов и ответов для проведения собеседования (интервью) по VueJS
3 |
4 | > Жми :star:, если тебе пригодился этот список. Если увидите ошибку, сообщите об этом в "Issues".
5 |
6 | Источник: [https://github.com/sudheerj/vuejs-interview-questions](https://github.com/sudheerj/vuejs-interview-questions)
7 | Перевод и редактура: [Владислав Гриценко](https://vk.com/abyss_dnb) - [Magisters](https://magisters.cc/)
8 |
9 | ### Содержание
10 | -------------------------------------------------------------------
11 | | № | Вопрос |
12 | |-- | ------
13 | |1 | [Что такое VueJS](#what-is-vuejs) |
14 | |2 | [Какие основные фичи у VueJS](#what-are-the-major-features-of-vuejs) |
15 | |3 | [Какие у VueJS методы жизненного цикла](#what-are-the-lifecycle-methods-of-vuejs)|
16 | |4 | [Какие есть директивы условного рендера во VueJS](#what-are-the-conditional-directives)|
17 | |5 | [В чем разница между директивами v-show и v-if](#what-is-the-difference-between-v-show-and-v-if-directives)|
18 | |6 | [Для чего используют директиву v-for](#what-is-the-purpose-of-v-for-directive)|
19 | |7 | [Расскажите об экземпляре класса Vue](#what-is-vue-instance)|
20 | |8 | [Как добиться условного рендеринга группы элементов или компонентов?](#how-do-you-achieve-conditional-group-of-elements)|
21 | |9 | [В каком случае вы переиспользуете элемент с атрибутом "key"?](#how-do-you-reuse-elements-with-key-attribute)|
22 | |10 | [Почему не стоит использовать директивы v-for и v-if на одном и том же элементе?](#why-should-not-use-if-and-for-directives-together-on-the-same-element)|
23 | |11 | [Почему нам нужно использовать атрибут key вместе с директивой v-for?](#why-do-you-need-to-use-key-attribute-on-for-directive)|
24 | |12 | [Какие методы массивов во vue запускают обновление отображения?](#what-are-the-array-detection-mutation-methods)|
25 | |13 | [Какие методы массивов во vue не запускают обновление отображения?](#what-are-the-array-detection-non-mutation-methods)|
26 | |14 | [Каковы особенности обнаружения изменений в массиве?](#what-are-the-caveats-of-array-changes-detection)|
27 | |15 | [Каковы особенности обнаружения изменений в объекте?](#what-are-the-caveats-of-object-changes-detection)|
28 | |16 | [How do you use for directive with a range?](#how-do-you-use-for-directive-with-a-range)|
29 | |17 | [How do you use for directive on template?](#how-do-you-use-for-directive-on-template)|
30 | |18 | [How do you use event handlers?](#how-do-you-use-event-handlers)|
31 | |19 | [What are the event modifiers provided by vue?](#what-are-the-event-modifiers-provided-by-vue)|
32 | |20 | [What are key modifiers?](#what-are-key-modifiers)|
33 | |21 | [How do you define custom key modifier aliases?](#how-do-you-define-custom-key-modifier-aliases)|
34 | |22 | [What are the supported System Modifier Keys?](#what-are-the-supported-system-modifier-keys)|
35 | |23 | [What are the supported Mouse Button Modifiers?](#what-are-the-supported-mouse-button-modifiers)|
36 | |24 | [How do you implement two way binding?](#how-do-you-implement-two-way-binding)|
37 | |25 | [What are the supported modifiers on model?](#what-are-the-supported-modifiers-on-model)|
38 | |26 | [What are components and give an example?](#what-are-components-and-give-an-example)|
39 | |27 | [What are props?](#what-are-props)|
40 | |28 | [When component needs a single root element?](#when-component-needs-a-single-root-element)|
41 | |29 | [How do you communicate from child to parent using events?](#how-do-you-communicate-from-child-to-parent-using-events)|
42 | |30 | [How do you implement model on custom input components?](#how-do-you-implement-model-on-custom-input-components)|
43 | |31 | [What are slots?](#what-are-slots)|
44 | |32 | [What is global registration in components?](#what-is-global-registration-in-components)|
45 | |33 | [Why do you need local registration?](#why-do-you-need-local-registration)|
46 | |34 | [What is the difference between local and global registration in module system?](#what-is-the-difference-between-local-and-global-registration-in-module-system)|
47 | |35 | [What are possible prop types?](#what-are-possible-prop-types)|
48 | |36 | [What is the data flow followed by props?](#what-is-the-data-flow-followed-by-props)|
49 | |37 | [What are non prop attributes?](#what-are-non-prop-attributes)|
50 | |38 | [Describe about validations available for props?](#describe-about-validations-available-for-props)|
51 | |39 | [How do you customize model directive for a component?](#how-do-you-customize-model-directive-for-a-component)|
52 | |40 | [What are the possible ways to provide transitions?](#What-are-the-possible-ways-to-provide-transitions)|
53 | |41 | [What is vue router and their features?](#what-is-vue-router-and-their-features)|
54 | |42 | [What are the steps to use vue router and give an example?](#what-are-the-steps-to-use-vue-router-and-give-an-example)|
55 | |43 | [What is dynamic route matching?](#what-is-dynamic-route-matching)|
56 | |44 | [How to make router param changes as reactive?](#how-to-make-router-param-changes-as-reactive)|
57 | |45 | [What is route matching priority?](#what-is-route-matching-priority)|
58 | |46 | [What are nested routes?](#what-are-nested-routes)|
59 | |47 | [What are single file components?](#what-are-single-file-components)|
60 | |48 | [Is Single File Components violating separation of concerns?](#is-single-file-components-violating-separation-of-concerns)|
61 | |49 | [What are the problems solved by Single File Components?](#what-are-the-problems-solved-by-single-file-components)|
62 | |50 | [What are filters?](#what-are-filters)|
63 | |51 | [What are the different ways to create filters?](#what-are-the-different-ways-to-create-filters)|
64 | |52 | [How do you chain filters](#how-do-you-chain-filters)|
65 | |53 | [Is it possible to pass parameters for filters?](#is-it-possible-to-pass-parameters-for-filters)|
66 | |54 | [What are plugins and their various services?](#what-are-plugins-and-their-various-services)|
67 | |55 | [ How to create a plugin?](#how-to-create-a-plugin)|
68 | |56 | [How to use a plugin?](#how-to-use-a-plugin)|
69 | |57 | [What are mixins?](#what-are-mixins)|
70 | |58 | [What are global mixins?](#what-are-global-mixins)|
71 | |59 | [How do you use mixins in CLI?](#how-do-you-use-mixins-in-cli)|
72 | |60 | [What are the merging strategies in mixins?](#what-are-the-merging-strategies-in-mixins)|
73 | |61 | [What are custom options merging strategies?](#what-are-custom-options-merging-strategies)|
74 | |62 | [What are custom directives?](#what-are-custom-directives)|
75 | |63 | [How do you register directives locally?](#how-do-you-register-directives-locally)|
76 | |64 | [What are the hook functions provided by directives?](#what-are-the-hook-functions-provided-by-directives)|
77 | |65 | [What are the directive Hook Arguments?](#what-are-the-directive-hook-arguments)|
78 | |66 | [How do you pass multiple values to a directive?](#how-do-you-pass-multiple-values-to-a-directive)|
79 | |67 | [What is function shorthand in directive hooks?](#what-is-function-shorthand-in-directive-hooks)|
80 | |68 | [What is the benefit of render functions over templates?](#what-is-the-benefit-of-render-functions-over-templates)|
81 | |69 | [What is a render function?](#What-is-a-render-function)|
82 | |70 | [Explain the structure of createElement with arguments](#explain-the-structure-of-createelement-with-arguments)|
83 | |71 | [How can you write duplicate virtual nodes in a component?](#how-can-you-write-duplicate-virtual-nodes-in-a-component)|
84 | |72 | [List down the template equivalents in render functions?](#list-down-the-template-equivalents-in-render-functions)|
85 | |73 | [What are functional components?](#what-are-functional-components)|
86 | |74 | [What are the similarities between VueJS and ReactJS?](#what-are-the-similarities-between-vuejs-and-reactjs)|
87 | |75 | [What is the difference between VueJS and ReactJS?](#what-is-the-difference-between-vuejs-and-reactjs)|
88 | |76 | [What are the advantages of VueJS over ReactJS?](#what-are-the-advantages-of-vuejs-over-reactjs)|
89 | |77 | [What are the advantages of ReactJS over VueJS?](#what-are-the-advantages-of-reactjs-over-vuejs)|
90 | |78 | [What are the differences between VueJS and AngularJS?](#What-are-the-differences-between-vuejs-and-angularjs)|
91 | |79 | [What are dynamic components?](#what-are-dynamic-components)|
92 | |80 | [What is the purpose of keep alive tag?](#what-is-the-purpose-of-keep-alive-tag)|
93 | |81 | [What are async components?](#what-are-async-components)|
94 | |82 | [What is the structure of async component factory?](#what-is-the-structure-of-async-component-factory)|
95 | |83 | [What are inline templates?](#what-are-inline-templates)|
96 | |84 | [What are X Templates?](#what-are-x-templates)|
97 | |85 | [What are recursive components?](#what-are-recursive-components)|
98 | |86 | [How do you resolve circular dependencies between components?](#how-do-you-resolve-circular-dependencies-between-components)|
99 | |87 | [How do you make sure vue application is CSP complaint?](#how-do-you-make-sure-vue-application-is-csp-complaint)|
100 | |88 | [What is the difference between full and runtime only builds?](#what-is-the-difference-between-full-and-runtime-only-builds)|
101 | |89 | [List down different builds of vuejs?](#list-down-different-builds-of-vuejs)|
102 | |90 | [How do you configure vuejs in webpack?](#how-do-you-configure-vuejs-in-webpack)|
103 | |91 | [What is the purpose of vuejs compiler?](#what-is-the-purpose-of-vuejs-compiler)|
104 | |92 | [What is Dev Tools and its purpose?](#what-is-dev-tools-and-its-purpose)|
105 | |93 | [What is the browser support of VueJS?](#what-is-the-browser-support-of-vuejs)|
106 | |94 | [How do you use various CDNs?](#how-do-you-use-various-cdns?)|
107 | |95 | [How do you force update?](#how-do-you-force-update)|
108 | |96 | [What is the purpose of vuejs once directive?](#what-is-the-purpose-of-vuejs-once-directive)|
109 | |97 | [How do you access the root instance?](#how-do-you-access-the-root-instance)|
110 | |98 | [List out top 10 organizations using Vuejs?](#list-out-top-10-organizations-using-vuejs)|
111 | |99 | [What is the purpose of renderError?](#what-is-the-purpose-of-rendererror)|
112 | |100| [How do you access parent instance?](#how-do-you-access-parent-instance)|
113 | |101| [What is vuex?](#what-is-vuex)|
114 | |102| [What are the major components of State Management Pattern?](#what-are-the-major-components-of-state-management-pattern)|
115 | |103| [How do you represent one way data flow in vuex?](#how-do-you-represent-one-way-data-flow-in-vuex)|
116 | |104| [What is a vuejs loader?](#what-is-a-vuejs-loader)|
117 | |105| [How do you configure vue loader in webpack?](#how-do-you-configure-vue-loader-in-webpack)|
118 | |106| [What are asset url transform rules?](#what-are-asset-url-transform-rules)|
119 | |107| [How do you work with preprocessors using vue loader?](#how-do-you-work-with-preprocessors-using-vue-loader)|
120 | |108| [What is scoped CSS?](#What-is-scoped-CSS)|
121 | |109| [Is it possible to mix both local and global styles?](#is-it-possible-to-mix-both-local-and-global-styles)|
122 | |110| [How do you use deep selectors?](#how-do-you-use-deepselectors)|
123 | |111| [Is parent styles leaked into child components in scoped css?](#is-parent-styles-leaked-into-child-components-in-scoped-css)|
124 | |112| [How do you style dynamic generated content using scoped css?](#how-do-you-style-dynamic-generated-content-using-scoped-css)|
125 | |113| [Is CSS modules supported in Vuejs?](#is-css-modules-supported-in-vuejs)|
126 | |114| [Can I use runtime builds for all templates?](#can-i-use-runtime-builds-for-all-templates)|
127 | |115| [How to use CSS modules in vuejs?](#how-to-use-css-modules-in-vuejs)|
128 | |116| [Can I use CSS modules for preprocessors?](#can-i-use-css-modules-for-preprocessors)|
129 | |117| [Is it possible to use custom inject name for CSS modules?](#is-it-possible-to-use-custom-inject-name-for-css-modules)|
130 | |118| [What is hot reloading in vue loader?](#what-is-hot-reloading-in-vue-loader)|
131 | |119| [What is the default behavior of hot reloading?](#what-is-the-default-behavior-of-hot-reloading)|
132 | |120| [How do you disable hot reloading explicitly?](#how-do-you-disable-hot-reloading-explicitly)|
133 | |121| [How do you use hot reloading?](#how-do-you-use-hot-reloading)|
134 | |122| [What are state preservation rules in hot reloading?](#what-are-state-preservation-rules-in-hot-reloading)|
135 | |123| [How to create functional components using vue loader?](#how-to-create-functional-components-using-vue-loader)|
136 | |124| [How do you access global properties of functional components?](#how-do-you-access-global-properties-of-functional-components)|
137 | |125| [How do you perform testing in vuejs?](#how-do-you-perform-testing-in-vuejs)|
138 | |126| [How do you apply linting for css?](#how-do-you-apply-linting-for-css)|
139 | |127| [How do you use eslint plugin?](#how-do-you-use-eslint-plugin)|
140 | |128| [What is the purpose of eslint loader?](#what-is-the-purpose-of-eslint-loader)|
141 | |129| [What is CSS extraction?](#what-is-css-extraction)|
142 | |130| [What are custom blocks?](#what-are-custom-blocks)|
143 | |131| [What are the features of stylelint?](#what-are-the-features-of-stylelint?)|
144 | |132| [What are the principles for vuex application structure?](#what-are-the-principles-for-vuex-application-structure)|
145 | |133| [Is Vuex supports hot reloading?](#is-vuex-supports-hot-reloading)|
146 | |134| [What is the purpose of hotUpdate API of vuex store?](#what-is-the-purpose-of-hotupdate-api-of-vuex-store)|
147 | |135| [How do you test mutations?](#how-do-you-test-mutations)|
148 | |136| [How do you test your getters?](#how-do-you-test-your-getters)|
149 | |137| [What is the procedure to run tests in node?](#what-is-the-procedure-to-run-tests-in-node)|
150 | |138| [What is the procedure to run tests in browser?](#what-is-the-procedure-to-run-tests-in-browser)|
151 | |139| [What is the purpose of strict mode in vuex?](#what-is-the-purpose-of-strict-mode-in-vuex)|
152 | |140| [Can I use strict mode in production environment?](#can-i-use-strict-mode-in-production-environment)|
153 | |141| [What is vuex plugin?](#what-is-vuex-plugin)|
154 | |142| [How do you mutate state in plugins?](#how-do-you-mutate-state-in-plugins)|
155 | |143| [What is vuex store?](#what-is-vuex-store)|
156 | |144| [What are the differences of vuex store and plain global object?](#what-are-the-differences-of-vuex-store-and-plain-global-object)|
157 | |145| [What is the reason not to update the state directly?](#what-is-the-reason-not-to-update-the-state-directly)|
158 | |146| [What is Single state tree?](#what-is-single-state-tree)|
159 | |147| [How do you install vuex?](#how-do-you-install-vuex)|
160 | |148| [Do I need promise for vuex?](#do-i-need-promise-for-vuex)|
161 | |149| [How do you display store state in vue components?](#how-do-you-display-store-state-in-vue-components)|
162 | |150| [How do you inject store into child components?](#how-do-you-inject-store-into-child-components)|
163 | |151| [What is mapState helper?](#what-is-mapstate-helper)|
164 | |152| [How do you combine local computed properties with mapState helper?](#how-do-you-combine-local-computed-properties-with-mapstate-helper)|
165 | |153| [Do you need to replace entire local state with vuex?](#do-you-need-to-replace-entire-local-state-with-vuex)|
166 | |154| [What are vuex getters?](#what-are-vuex-getters?)|
167 | |155| [What is a property style access?](#what-is-a-property-style-access)|
168 | |156| [What is a method style access?](#what-is-a-method-style-access)|
169 | |157| [What is mapGetter helper?](#what-is-mapgetter-helper)|
170 | |158| [What are mutations?](#what-are-mutations)|
171 | |159| [How do you commit with payload?](#how-do-you-commit-with-payload)|
172 | |160| [What is object style commit?](#what-is-object-style-commit)|
173 | |161| [What are the caveats with vuex mutations?](#what-are-the-caveats-with-vuex-mutations)|
174 | |162| [Why mutations should be synchronous?](#why-mutations-should-be-synchronous)|
175 | |163| [How do you perform mutations in components?](#how-do-you-perform-mutations-in-components)|
176 | |164| [Is it mandatory to use constants for mutation types?](#is-it-mandatory-to-use-constants-for-mutation-types)|
177 | |165| [How do you perform asynchronous operations?](#how-do-you-perform-asynchronous-operations)|
178 | |166| [What are differences between mutations and actions?](#what-are-differences-between-mutations-and-actions)|
179 | |167| [Give an example usage of actions?](#give-an-example-usage-of-actions?)|
180 | |168| [How do you dispatch actions?](#how-do-you-dispatch-actions)|
181 | |169| [Can you dispatch an action using payload or object?](#can-you-dispatch-an-action-using-payload-or-object)|
182 | |170| [Can I use styled components in vuejs?](#can-i-use-styled-components-in-vuejs)|
183 | |171| [How do you dispatch actions in components?](#how-do-you-dispatch-actions-in-components)|
184 | |172| [How do you compose actions?](#how-do-you-compose-actions)|
185 | |173| [What are modules in vuex?](#what-are-modules-in-vuex)|
186 | |174| [What is module local state?](#what-is-module-local-state)|
187 | |175| [What is namespacing in vuex](#what-is-namespacing-in-vuex)|
188 |
189 | 1. ### Что такое VueJS?
190 | **Vue.js** это прогрессивный open-source фреймворк для разработки пользовательских интерфейсов, который стремиться быть легко внедряемым в процесс разработки. Ядро библиотеки VueJS фокусируется только на "слое отображения", потому его можно легко интегрировать с множеством библиотек и внедрить в существующие проекты.
191 | 2. ### Какие основные фичи у VueJS?
192 | Ниже представлен список основных фич доступных во VueJS
193 | 1. **Виртуальный DOM:** VueJS использует виртульный DOM, такой же подход, как и у других существующих фреймворков (ReactJS, Ember и т.п.). Виртаульный DOM - это хранимая в памяти репрезентация оригинального HTML DOM-дерева, которая обновляется и изменяется не затрагивая при этом оригинальный DOM.
194 | 2. **Компоненты:** Используется для создания переиспользуемых компонентов в любых приложениях на VueJS.
195 | 3. **Шаблоны:** VueJS предоставляет возможности шаблонизации, которая связывает HTML-разметку с данными компонента и экземпляра класса Vue.
196 | 4. **Реактивность:** VueJS дает возможность создавать реактивные односторонние и двусторонние связи данных с их отображением.
197 | 5. **Роутинг:** Перемещение между страницами реализовано при помощи библиотеки vue-router
198 | 6. **Легковесный:** VueJS один из самых легковесных фреймворков в сравнении с другими
199 | 3. ### Какие у VueJS методы жизненного цикла?
200 | Методы жизненного цикла - это ответ на вопрос, как работает библиотека "за кулисами". Используя эти методы, вы знаете в какой момент ваш компонент создан, добавлен в DOM-дерево, обновлен или разрушен. Давайте посмотрим на эту диаграмму, перед тем как обсудить каждый метод отдельно,
201 |
202 |
203 |
204 | 1. **Создание (инициализация):**
205 | Методы, вызываемые до и во время создания компонента, позволяют выполнять действия до того, как компонент будет добавлен в DOM. Вы можете использовать эти методы если хотите установить какие-то данные или что-то настроить в момент рендера на клиенте или сервере. Методы создания, в отличие от остальных методов, вызываются в момент серверного рендера.
206 | 1. beforeCreate:
207 | Этот метод вызывается в самом начале инициализации компонента. В этот момент данные и события компонента готовятся к активации. На этом этапе данные еще не реактивны, а события все еще не установлены.
208 | ```javascript
209 | new Vue({
210 | data: {
211 | count: 10
212 | },
213 | beforeCreate: function () {
214 | console.log('Nothing gets called at this moment')
215 | // `this` указывает на VM (view-model) инстанс
216 | console.log('count is ' + this.count); // count = undefined
217 | }
218 | })
219 | ```
220 | 2. created:
221 | Этот метод вызывается когда Vue установил все события и наблюдает за данными. На этом этапе все события активны и имеют доступ к реактивным данным компонента, не смотря на то, что компонент еще не смонтирован или отрендерен.
222 | ```javascript
223 | new Vue({
224 | data: {
225 | count: 10
226 | },
227 | created: function () {
228 | // `this` указывает на VM (view-model) инстанс
229 | console.log('count is: ' + this.count) // count = 10
230 | }
231 | })
232 | ```
233 | **ВНИМАНИЕ:** Запомните, что вы не имеете доступа к DOM-элементу или целевому монтируемому элементу (this.$el) внутри методов создания компонента.
234 | 2. **Монтирование (вставка в DOM):**
235 | Методы монтирования самые используемые методы и позволяют получить доступ к компоненту непосредственно перед и после первого рендера.
236 | 1. beforeMount:
237 | Этот метод позволяет получить доступ к компоненту непосредственно перед его монтированием (первым рендером).
238 | ```javascript
239 | new Vue({
240 | beforeMount: function () {
241 | // `this` points to the view model instance
242 | console.log(`this.$el вот-вот будет вмонтирован`);
243 | }
244 | })
245 | ```
246 | 2. mounted:
247 | Это самый популярный метод в котором вы имеете полный доступ к реактивным данным, компоненты, шаблону и отрендеренному DOM (через this.$el). Самое распространенное использование, это получение данных для компонента (например, через AJAX).
248 | ```javascript
249 |
250 |
Это текст в компоненте
251 |
252 | new Vue({
253 | el: ‘#app’,
254 | mounted: function() {
255 | console.log(this.$el.textContent); // "Это текст в компоненте"
256 | }
257 | })
258 | ```
259 | 3. **Обновление (поиск отличий и перерендер):**
260 | Методы обновления вызываются когда реактивные данные были изменены, или что-то еще вызвало перерендер.
261 | 1. beforeUpdate:
262 | Этот методы вызывается после изменений данных в компоненте, но перед применением этих изменений на DOM.
263 | ```javascript
264 |
265 |
{{counter}}
266 |
267 | ...// другой код
268 | new Vue({
269 | el: '#app',
270 | data() {
271 | return {
272 | counter: 0
273 | }
274 | },
275 | created: function() {
276 | setInterval(() => {
277 | this.counter++
278 | }, 1000)
279 | },
280 |
281 | beforeUpdate: function() {
282 | console.log(this.counter) // Логирует значение счетчика каждую секунду, перед обновлением DOM.
283 | }
284 | })
285 | ```
286 | 2. updated:
287 | This hook runs after data changes on your component and the DOM re-renders.
288 | ```javascript
289 |
290 |
{{counter}}
291 |
292 | ...// другой код
293 | new Vue({
294 | el: '#app',
295 | data() {
296 | return {
297 | counter: 0
298 | }
299 | },
300 | created: function() {
301 | setInterval(() => {
302 | this.counter++
303 | }, 1000)
304 | },
305 | updated: function() {
306 | console.log(+this.$refs['dom'].textContent === this.counter) // логирует true каждую секунду
307 | }
308 | })
309 | ```
310 | 4. **Демонтирование (отключение):**
311 | Методы демонтирования позволяют выполнять действия когда ваш компонент по каким-либо причинам демонтируется (например, из-за v-if). В эти моменты можно очистить какие-либо даные из памяти или отправить аналитические данные.
312 | 1. beforeDestroy:
313 | `beforeDestroy` вызывается прямо перед отключением. Если вы хотите очистить события или подписки на какие-либо реактивные данные, это пожалуй лучший момент чтобы сделать это. Ваш компонент все еще доступен и полностью функционирует.
314 | ```javascript
315 | new Vue ({
316 | data() {
317 | return {
318 | message: 'Добро пожаловать в мир VueJS'
319 | }
320 | },
321 |
322 | beforeDestroy: function() {
323 | this.message = null
324 | delete this.message
325 | }
326 | })
327 | ```
328 | 2. destroyed:
329 | Этот метод вызывается сразу после того, как компонент был полностью разрушен, директивы отвязаны и обработчики событий удалены.
330 | ```javascript
331 | new Vue ({
332 | destroyed: function() {
333 | console.log(this) // Здесь нечего логировать
334 | }
335 | })
336 | ```
337 |
338 | 4. ### Какие есть директивы условного рендера во VueJS?
339 | VueJS предлагает набор директив для показа или скрытия HTML-элементов, компонентов в зависимости от условий. Доступны следующие директивы: **v-if, v-else, v-else-if and v-show**
340 | **1. v-if:** Эта директива добавляет или удаляет DOM елемент в зависимости от результата указанного выражения. Например, в коде ниже кнопка не будет показана, если в isLoggedIn записано false.
341 | ```javascript
342 |
343 | ```
344 | Ты можешь также использовать эту директиву на нескольких элементах, обернув их в `` и использую на нем директиву. Например, ты можешь одновременно скрывать/показывать и подпись и кнопку опираясь на условие.
345 | ```javascript
346 |
347 |
350 | ```
351 | **2. v-else:** Эта директива используется для отображения контента только если выражению для v-if возвращает false. Это очень схоже с блоком else в любом языке программирования для отображения альтернативного контента. В отличие от v-if и v-else-if не требует значения.
352 | Например, v-else можно использовать для отображения кнопки "Войти" если isLoggedIn === false (не авторизован).
353 | ```javascript
354 |
355 |
356 | ```
357 | **3. v-else-if:** Эта директива используется если нам необходимо проверить более одного условия и для каждого отобразить свой контент. Например, мы хотим отобразить какой-то текст вместо кнопки "Войти" когда ifLoginDisabled === true. При помощи v-else у нас не получится это реализовать.
358 | ```javascript
359 |
360 |
361 |
362 | ```
363 |
364 | **4. v-show:** Эта директива похожа на v-if, но она рендерит все элементы в DOM-дерево, а затем применяет на них CSS-свойство display для показа/скрытия элементов. Эта директива рекомендуется если элементы переключаются между состояниями очень часто.
365 | ```javascript
366 | Добро пожаловать, {{user.name}}
367 | ```
368 | 5. ### В чем разница между директивами v-show и v-if?
369 | Ниже указаны основные различия между **v-show** и **v-if**:
370 | 1. v-if рендерит элемент в DOM-дереве только если выражение истинно, в то время как v-show рендерит их при любом условии, но скрывает при помощи CSS.
371 | 2. v-if поддерживает директивы v-else и v-else-if, в то время как v-show не имеет альтернативной директивы.
372 | 3. v-if требует больше ресурсов при переключении состояния для рендера, а v-show позволяет делать это максимально быстро, но с соответствующими ограничениями.
373 | 4. v-if поддерживает ``, а v-show нет.
374 |
375 | 6. ### Для чего используют директиву v-for?
376 | Встроенная директива v-for позволяет нам проходить по элементам массива, т.е. это привычный нам цикл в котором мы можем обратиться к содержимому каждого элемента. Как правило, это массив объектов.
377 | 1. Пример с массивом:
378 | ```javascript
379 |
380 |
381 | {{ index }} - {{ item.message }}
382 |
383 |
384 |
385 | var vm = new Vue({
386 | el: '#list',
387 | data: {
388 | items: [
389 | { message: 'John' },
390 | { message: 'Locke' }
391 | ]
392 | }
393 | })
394 | ```
395 | Вы также можете использовать `of` в качестве разделителя вместо `in`, также как в итераторах javascript.
396 |
397 | 2. Пример с объектом:
398 | ```javascript
399 |
400 |
401 | {{ index }}. {{ key }}: {{ value }}
402 |
403 |
404 |
405 | var vm = new Vue({
406 | el: '#object',
407 | data: {
408 | user: {
409 | firstName: 'John',
410 | lastName: 'Locke',
411 | age: 30
412 | }
413 | }
414 | })
415 | ```
416 | 7. ### Расскажите об экземпляре класса Vue
417 | Каждое Vue-приложение работает на экзэмпляре класса Vue, который создается с помощью функции конструктора Vue(). Полный пример создания экзэмпляра vue:
418 | ```javascript
419 | var vm = new Vue({
420 | // параметры
421 | })
422 | ```
423 | Функция принимает в качестве аргумента объект параметров. Полный список параметров функции конструктора vue вы можете посмотреть в официальной документации.
424 | 8. ### Как добиться условного рендеринга группы элементов или компонентов?
425 | Мы можем добиться условного рендеринга группы элементов или компонентов применив директиву **v-if** на ``, этим невидимым элементом мы обернем необходимый для скрытия контент. Пример такого приема можете посмотреть ниже:
426 | ```javascript
427 |
428 |
Name
429 |
Address
430 |
Contact Details
431 |
432 | ```
433 | 9. ### В каком случае вы переиспользуете элемент с атрибутом "key"?
434 | Vue всегда рендерить элементы максимально эффективно. Для этого он пытается переиспользовать элементы вместо того, чтобы создавать новые с нуля. Однако, такой подход может вызывать проблемы в сценариях с одинаковыми элементами. Например, если вы попытаетесь отрендерить input одновременно и в `v-if` и в `v-else`, значение будет сохранено и перенесено из "другого" `input`. Код примера ниже:
435 | ```javascript
436 |
437 |
438 |
439 |
440 |
441 |
442 |
443 |
444 | ```
445 | В следующем случае элемент не будет переиспользован и значения будут разделены между уникальными input благодаря применения атрибута **key**. Код примера:
446 | ```javascript
447 |
448 |
449 |
450 |
451 |
452 |
453 |
454 |
455 | ```
456 | Можете убедиться, что в коде выше `input`-ы теперь независимы и не влияют друг на друга.
457 | 10. ### Стоит ли использовать директивы v-for и v-if на одном и том же элементе?
458 | Крайне не рекомендуется использовать v-for и v-if на одном и том же элементе, так как v-for имеет более высокий приоритет и такая фильтрация элементов оказывается неэффективной, а скорее даже, бесполезной, так как цикл пройдет по всем элементам. Есть несколько случаев, когда эта практика может показаться привлекательной для новичков:
459 | 1. Фильтрация списка
460 | В этом коде мы проверяем стоит ли отображать пользователя в списке **(плохой пример)**
461 | ```javascript
462 |
463 |
468 | {{ user.name }}
469 |
470 |
471 | ```
472 | Вместо такого подхода, будет намного производительнее использовать **v-for** на `computed` с отфильтрованным массивом **(хороший пример)**:
473 | ```javascript
474 | computed: {
475 | activeUsers: function () {
476 | return this.users.filter(function (user) {
477 | return user.isActive
478 | })
479 | }
480 | }
481 | ...... //
482 | ...... //
483 |
484 |
487 | {{ user.name }}
488 |
489 |
490 |
491 | ```
492 | 2. Скрытие всего списка
493 | В этом примере мы проверяете стоит ли отображать список **(плохой пример)**
494 | ```javascript
495 |
496 |
501 | {{ user.name }}
502 |
503 |
504 | ```
505 | Этого можно добиться используя v-if директиву на родительском элементе, чтобы не делать проверку каждую итерацию цикла
506 | ```javascript
507 |
508 |
512 | {{ user.name }}
513 |
514 |
515 | ```
516 | 11. ### Почему нам нужно использовать атрибут key вместе с директивой v-for?
517 | Для того чтобы отслеживать каждый уникальный элемент, и в дальнейшем эффективно их переиспользовать, нам нужен атрибут `key` с уникальным значением для каждого элемента в цикле `v-for`. В идеале это должен быть уникальный идентификатор сущности. Пример кода:
518 | ```javascript
519 |
520 | {{item.name}}
521 |
522 | ```
523 | **Замечание:** Не стоит использовать в качестве ключа не примитивные типы данных, например объекты или массивы. Лучше использовать строки или числа.
524 | 12. ### Какие методы массивов во vue запускают обновление отображения?
525 | Следующие методы при их использовании на реактивном массиве вызовут обновление отображения:
526 | 1. push()
527 | 2. pop()
528 | 3. shift()
529 | 4. unshift()
530 | 5. splice()
531 | 6. sort()
532 | 7. reverse()
533 | 13. ### Какие методы массивов во vue не запускают обновление отображения?
534 | Методы, которые не мутируют оригинальный массив, но всегда возвращают новый массив, называют немутационными методами. Следующие методы не запускают обновление отображения:
535 | 1. filter()
536 | 2. concat()
537 | 3. slice()
538 |
539 | Для примера давайте возьмем список задач, и перезапишем его на основе фильтрующей функции по статусу задачи:
540 | ```javascript
541 | vm.todos = vm.todos.filter(function (todo) {
542 | return todo.status.match(/Completed/)
543 | })
544 | ```
545 | Данный подход не даст желаемого результата, из-за внутренней реализации списков во VueJS.
546 | 14. ### Каковы особенности обнаружения изменений в массиве?
547 | Vue не может определить изменения в массиве в следующих случаях:
548 | 1. Когда вы напрямую меняете элемент массива, обращаясь по индексу, например:
549 | ```javascript
550 | vm.todos[indexOfTodo] = newTodo
551 | ```
552 | 2. Когда вы меняете длину массива напрямую, например:
553 | ```javascript
554 | vm.todos.length = todosLength
555 | ```
556 | Вы можете достичь этих целей при помощи методов `set` и `splice`, например:
557 | **Первый случай**
558 | ```javascript
559 | // Vue.set
560 | Vue.set(vm.todos, indexOfTodo, newTodoValue)
561 | // или
562 | // Array.prototype.splice
563 | vm.todos.splice(indexOfTodo, 1, newTodoValue)
564 | ```
565 | **Второй случай**
566 | ```javascript
567 | vm.todos.splice(todosLength)
568 | ```
569 | 15. ### Каковы особенности обнаружения изменений в объекте?
570 | Vue не может определить удаление и добавление новых свойств у объекта. Давайте рассмотрим пример:
571 | ```javascript
572 | var vm = new Vue({
573 | data: {
574 | user: {
575 | name: 'John'
576 | }
577 | }
578 | })
579 |
580 | // `vm.user.name` реактивное свойство
581 |
582 | vm.email = john@email.com // `vm.email` не реактивное
583 | ```
584 | Для того чтобы реализовать этот сценарий мы можем использовать метод Vue.set(object, key, value) или Object.assign(),
585 | ```javascript
586 | Vue.set(vm.user, 'email', john@email.com);
587 | // или
588 | vm.user = Object.assign({}, vm.user, {
589 | email: john@email.com
590 | })
591 | ```
592 | 16. ### How do you use v-for directive with a range?
593 | You can also use integer type(say 'n') for v-for directive which repeats the element many times.
594 | ```javascript
595 |
596 | {{ n }}
597 |
598 | ```
599 | It displays the number 1 to 20.
600 | 17. ### How do you use v-for directive on template?
601 | Just similar to v-if directive on template, you can also use a `` tag with v-for directive to render a block of multiple elements. Let's take a todo example,
602 | ```javascript
603 |
604 |
605 |
{{ todo.title }}
606 |
607 |
608 |
609 | ```
610 | 18. ### How do you use event handlers?
611 | You can use event handlers in vue similar to plain javascript. The method calls also support the special $event variable.
612 | ```javascript
613 |
616 |
617 | methods: {
618 | show: function (message, event) {
619 | // now we have access to the native event
620 | if (event) event.preventDefault()
621 | console.log(message);
622 | }
623 | }
624 | ```
625 | 19. ### What are the event modifiers provided by vue?
626 | Normally, javascript provides event.preventDefault() or event.stopPropagation() inside event handlers. You can use methods provided by vue, but these methods are meant for data logic instead of dealing with DOM events. Vue provides below event modifiers for v-on and these modifiers are directive postfixes denoted by a dot.
627 | 1. .stop
628 | 2. .prevent
629 | 3. .capture
630 | 4. .self
631 | 5. .once
632 | 6. .passive
633 |
634 | Let's take an example of stop modifier,
635 | ```html
636 |
637 |
638 | ```
639 | You can also chain modifiers as below,
640 | ```html
641 |
642 |
643 | ```
644 | 20. ### What are key modifiers?
645 | Vue supports key modifiers on `v-on` for handling keyboard events. Let's take an example of keyup event with enter keycode.
646 | ```html
647 |
648 |
649 | ```
650 | Remembering all the key codes is really difficult. It supports the full list of key codes aliases
651 | 1. .enter
652 | 2. .tab
653 | 3. .delete (captures both “Delete” and “Backspace” keys)
654 | 4. .esc
655 | 5. .space
656 | 6. .up
657 | 7. .down
658 | 8. .left
659 | 9. .right
660 |
661 | Now the above keyup code snippet can be written with aliases as follows,
662 | ```javascript
663 |
664 | // (OR)
665 |
666 |
667 | ```
668 | **The use of keyCode events is deprecated and may not be supported in new browsers.**
669 | 21. ### How do you define custom key modifier aliases?
670 | You can define custom key modifier aliases via the global `config.keyCodes`. There are few guidelines for the properties
671 | 1. You can't use camelCase. Instead you can use kebab-case with double quotation marks
672 | 2. You can define multiple values in an array format
673 | ```javascript
674 | Vue.config.keyCodes = {
675 | f1: 112,
676 | "media-play-pause": 179,
677 | down: [40, 87]
678 | }
679 | ```
680 | 22. ### What are the supported System Modifier Keys?
681 | Vue supports below modifiers to trigger mouse or keyboard event listeners when the corresponding key is pressed,
682 | 1. .ctrl
683 | 2. .alt
684 | 3. .shift
685 | 4. .meta
686 |
687 | Lets take an example of control modifier with click event,
688 | ```javascript
689 |
690 |
Do something
691 | ```
692 | 23. ### What are the supported Mouse Button Modifiers?
693 | Vue supports below mouse button modifiers
694 | 1. .left
695 | 2. .right
696 | 3. .middle
697 |
698 | For example, the usage of `.right` modifier as below
699 | ```javascript
700 |
705 | ```
706 | 24. ### How do you implement two-way binding?
707 | You can use the `v-model` directive to create two-way data bindings on form input, textarea, and select elements. Lets take an example of it using input component,
708 | ```javascript
709 |
710 |
The message is: {{ message }}
711 | ```
712 | Remember, v-model will ignore the initial `value`, `checked` or `selected` attributes found on any form elements. So it always use the Vue instance data as the source of truth.
713 | 25. ### What are the supported modifiers on model?
714 | There are three modifiers supported for v-model directive.
715 |
716 | **1. lazy:** By default, v-model syncs the input with the data after each input event. You can add the lazy modifier to instead sync after change events.
717 | ```javascript
718 |
719 |
720 | ```
721 | **2. number:** If you want user input to be automatically typecast as a number, you can add the number modifier to your v-model. Even with type="number", the value of HTML input elements always returns a string. So, this typecast modifier is required.
722 | ```javascript
723 |
724 | ```
725 | **3. trim:** If you want whitespace from user input to be trimmed automatically, you can add the trim modifier to your v-model.
726 | ```javascript
727 |
728 | ```
729 | 26. ### What are components and give an example?
730 | Components are reusable Vue instances with a name. They accept the same options as new Vue, such as data, computed, watch, methods, and lifecycle hooks(except few root-specific options like el). Lets take an example of counter component,
731 | ```javascript
732 | // Define a new component called button-counter
733 | Vue.component('button-counter', {
734 | template: ''
735 | data: function () {
736 | return {
737 | count: 0
738 | }
739 | },
740 | })
741 | ```
742 | Let's use this component inside a root Vue instance created with new Vue
743 | ```javascript
744 |
745 |
746 |
747 |
748 | var vm = new Vue({ el: '#app' });
749 | ```
750 | 27. ### What are props?
751 | Props are custom attributes you can register on a component. When a value is passed to a prop attribute, it becomes a property on that component instance. You can pass those list of values as props option and use them as similar to data variables in template.
752 | ```javascript
753 | Vue.component('todo-item', {
754 | props: ['title'],
755 | template: '
{{ title }}
'
756 | })
757 | ```
758 | Once the props are registered, you can pass them as custom atrtributes.
759 | ```javascript
760 |
761 | ```
762 | 28. ### When component needs a single root element?
763 | Every component must have a single root element **when template has more than one element**. In this case, you need to wrap the elements with a parent element.
764 | ```javascript
765 |
766 |
{{ title }}
767 |
768 |
769 | ```
770 | Otherwise there will an error throwing, saying that "Component template should contain exactly one root element...".
771 | 29. ### How do you communicate from child to parent using events?
772 | If you want child wants to communicate back up to the parent, then emit an event from child using `$event` object to parent,
773 | ```javascript
774 | Vue.component('todo-tem', {
775 | props: ['todo'],
776 | template: `
777 |
778 |
{{ todo.title }}
779 |
782 |
783 |
784 | `
785 | })
786 | ```
787 | Now you can use this todo-item in parent component to access the count value.
788 | ```javascript
789 |
790 |
791 |
794 |
795 |
796 | Total todos count is {{total}}
797 | ```
798 | 30. ### How do you implement model on custom input components?
799 | The custom events can also be used to create custom inputs that work with v-model. The inside the component must follow below rules,
800 | 1. Bind the value attribute to a value prop
801 | 2. On input, emit its own custom input event with the new value.
802 | Let's take a custom-input component as an example,
803 | ```javascript
804 | Vue.component('custom-input', {
805 | props: ['value'],
806 | template: `
807 |
811 | `
812 | })
813 | ```
814 | Now you can use `v-model` with this component,
815 | ```javascript
816 |
817 | ```
818 | 31. ### What are slots?
819 | Vue implements a content distribution API using the element to serve as distribution outlets for content created after after the current Web Components spec draft. Let's create an alert component with slots for content insertion,
820 | ```javascript
821 | Vue.component('alert', {
822 | template: `
823 |
824 | Error!
825 |
826 |
827 | `
828 | })
829 | ```
830 | Now you can insert dynamic content as below,
831 | ```javascript
832 |
833 | There is an issue with in application.
834 |
835 | ```
836 | 32. ### What is global registration in components?
837 | The components which are globally registered can be used in the template of any root Vue instance (new Vue) created after registration. In the global registration, the components created using Vue.component as below,
838 | ```javascript
839 | Vue.component('my-component-name', {
840 | // ... options ...
841 | })
842 | ```
843 | Let's take multiple components which are globally registered in the vue instance,
844 | ```javascript
845 | Vue.component('component-a', { /* ... */ })
846 | Vue.component('component-b', { /* ... */ })
847 | Vue.component('component-c', { /* ... */ })
848 |
849 | new Vue({ el: '#app' })
850 | ```
851 | The above components can be used in the vue instance,
852 | ```javascript
853 |
854 |
855 |
856 |
857 |
858 | ```
859 | Remember that the components can be used in subcomponents as well.
860 | 33. ### Why do you need local registration?
861 | Due to global registration, even if you don't use the component it could still be included in your final build. So it will create unnecessary javascript in the application. This can be avoided using local registration with the below steps,
862 | 1. First you need to define your components as plain JavaScript objects
863 | ```javascript
864 | var ComponentA = { /* ... */ }
865 | var ComponentB = { /* ... */ }
866 | var ComponentC = { /* ... */ }
867 | ```
868 | Locally registered components will not be available in sub components. In this case, you need to add them in components section
869 | ```javascript
870 | var ComponentA = { /* ... */ }
871 |
872 | var ComponentB = {
873 | components: {
874 | 'component-a': ComponentA
875 | },
876 | // ...
877 | }
878 | ```
879 | 2. You can use the components in the components section of the vue instance,
880 | ```javascript
881 | new Vue({
882 | el: '#app',
883 | components: {
884 | 'component-a': ComponentA,
885 | 'component-b': ComponentB
886 | }
887 | })
888 | ```
889 | 34. ### What is the difference between local and global registration in module system?
890 | In **local registration**, you need to create each component in components folder(optional but it is recommended) and import them in another component file components section. Let's say you want to register component A and B in component C, the configuration seems as below,
891 | ```javascript
892 | import ComponentA from './ComponentA'
893 | import ComponentB from './ComponentC'
894 |
895 | export default {
896 | components: {
897 | ComponentA,
898 | ComponentB
899 | },
900 | // ...
901 | }
902 | ```
903 | Now both ComponentA and ComponentB can be used inside ComponentC‘s template.
904 |
905 | In **global registration**, you need to export all common or base components in a separate file. But some of the popular bundlers like `webpack` make this process simpler by using `require.context` to globally register base components in the below entry file(one-time).
906 |
907 | ```javascript
908 | import Vue from 'vue'
909 | import upperFirst from 'lodash/upperFirst'
910 | import camelCase from 'lodash/camelCase'
911 |
912 | const requireComponent = require.context(
913 | // The relative path of the components folder
914 | './components',
915 | // Whether or not to look in subfolders
916 | false,
917 | // The regular expression used to match base component filenames
918 | /Base[A-Z]\w+\.(vue|js)$/
919 | )
920 |
921 | requireComponent.keys().forEach(fileName => {
922 | // Get component config
923 | const componentConfig = requireComponent(fileName)
924 |
925 | // Get PascalCase name of component
926 | const componentName = upperFirst(
927 | camelCase(
928 | // Strip the leading `./` and extension from the filename
929 | fileName.replace(/^\.\/(.*)\.\w+$/, '$1')
930 | )
931 | )
932 |
933 | // Register component globally
934 | Vue.component(
935 | componentName,
936 | // Look for the component options on `.default`, which will
937 | // exist if the component was exported with `export default`,
938 | // otherwise fall back to module's root.
939 | componentConfig.default || componentConfig
940 | )
941 | })
942 | ```
943 | 35. ### What are possible prop types?
944 | You can declare props with type or without type. But it is recommended to have prop types because it provides the documentation for the component and warns the developer for any incorrect data type being assigned.
945 | ```javascript
946 | props: {
947 | name: String,
948 | age: Number,
949 | isAuthenticated: Boolean,
950 | phoneNumbers: Array,
951 | address: Object
952 | }
953 | ```
954 | As mentioned in the above code snippet, you can list props as an object, where the properties’ names and values contain the prop names and types, respectively.
955 | 36. ### What is the data flow followed by props?
956 | All props follows a one-way-down binding between the child property and the parent one. i.e, When the parent property is updated then that latest prop value will be passed down to the child, but not the otherway(child to parent) around. The child component should not mutate the prop otherwise it throws a warning in the console.
957 | The possible mutation cases can be solved as below,
958 | 1. When you try to use parent prop as initial value for child property:
959 |
960 | In this case you can define a local property in child component and assign parent value as initial value
961 | ```javascript
962 | props: ['defaultUser'],
963 | data: function () {
964 | return {
965 | username: this.defaultUser
966 | }
967 | }
968 | ```
969 | 2. When you try to transform the parent prop:
970 |
971 | You can define a computed property using the prop’s value,
972 | ```javascript
973 | props: ['environment'],
974 | computed: {
975 | localEnvironment: function () {
976 | return this.environment.trim().toUpperCase()
977 | }
978 | }
979 | ```
980 | 37. ### What are non prop attributes?
981 | A non-prop attribute is an attribute that is passed to a component, but does not have a corresponding prop defined.
982 | For example, If you are using a 3rd-party custom-input component that requires a `data-tooltip` attribute on the input then you can add this attribute to component instance,
983 | ```javascript
984 |
985 | ```
986 | If you try to pass the props from parent component the child props with the same names will be overridden. But props like `class` and `style` are exception to this, these values will be merged in the child component.
987 | ```javascript
988 | //Child component
989 |
990 | //Parent component
991 |
992 | ```
993 | 38. ### Describe about validations available for props?
994 | Vue provides validations such as types, required fields, default values along with customized validations. You can provide an object with validation requirements to the value of props as below,
995 | Let's take an example of user profile Vue component with possible validations,
996 | ```javascript
997 | Vue.component('user-profile', {
998 | props: {
999 | // Basic type check (`null` matches any type)
1000 | age: Number,
1001 | // Multiple possible types
1002 | identityNumber: [String, Number],
1003 | // Required string
1004 | email: {
1005 | type: String,
1006 | required: true
1007 | },
1008 | // Number with a default value
1009 | minBalance: {
1010 | type: Number,
1011 | default: 10000
1012 | },
1013 | // Object with a default value
1014 | message: {
1015 | type: Object,
1016 | // Object or array defaults must be returned from
1017 | // a factory function
1018 | default: function () {
1019 | return { message: 'Welcome to Vue' }
1020 | }
1021 | },
1022 | // Custom validator function
1023 | location: {
1024 | validator: function (value) {
1025 | // The value must match one of these strings
1026 | return ['India', 'Singapore', 'Australia'].indexOf(value) !== -1
1027 | }
1028 | }
1029 | }
1030 | })
1031 | ```
1032 | 39. ### How do you customize model directive for a component?
1033 | The v-model directive on a component uses **value** as the prop and **input** as the event, but some input types such as `checkboxes` and `radio buttons` may need to use the value attribute for a server side value. In this case, it is preferred to customize model directive. Let's take an example of checkbox component,
1034 | ```javascript
1035 | Vue.component('custom-checkbox', {
1036 | model: {
1037 | prop: 'checked',
1038 | event: 'change'
1039 | },
1040 | props: {
1041 | checked: Boolean
1042 | },
1043 | template: `
1044 |
1049 | `
1050 | })
1051 | ```
1052 | Now you can use v-model on this customized component as below,
1053 | ```javascript
1054 |
1055 | ```
1056 | The selectFramework property will be passed to the checked prop and same property will be updated when custom checkbox component emits a change event with a new value.
1057 | 40. ### What are the possible ways to provide transitions?
1058 | There are many ways Vue provides transition effects when items are inserted, updated, or removed from the DOM. Below are the possible ways,
1059 | 1. Automatically apply classes for CSS transitions and animations
1060 | 2. Integrate 3rd-party CSS animation libraries. For example, Animate.css
1061 | 3. Use JavaScript to directly manipulate the DOM during transition hooks
1062 | 4. Integrate 3rd-party JavaScript animation libraries. For example, Velocity.js
1063 | 41. ### What is vue router and their features?
1064 | Vue Router is a official routing library for single-page applications designed for use with the Vue.js framework. Below are their features,
1065 | 1. Nested route/view mapping
1066 | 2. Modular, component-based router configuration
1067 | 3. Route params, query, wildcards
1068 | 4. View transition effects powered by Vue.js' transition system
1069 | 5. Fine-grained navigation control
1070 | 6. Links with automatic active CSS classes
1071 | 7. HTML5 history mode or hash mode, with auto-fallback in IE9
1072 | 8. Restore scroll position when going back in history mode
1073 |
1074 | 42. ### What are the steps to use vue router and give an example?
1075 | It is easy to integrate vue router in the vue application. Let us see the example with step by step instructions.
1076 |
1077 | **Step 1:** Configure router link and router view in the template
1078 | ```javascript
1079 |
1080 |
1081 |
1082 |
1083 |
Welcome to Vue routing app!
1084 |
1085 |
1086 | Home
1087 | Services
1088 |
1089 |
1090 |
1091 |
1092 | ```
1093 | **Step 2:** Import Vue and VueRouter packages and then apply router
1094 | ```javascript
1095 | import Vue from 'vue';
1096 | import VueRouter from 'vue-router';
1097 |
1098 | Vue.use(VueRouter)
1099 | ```
1100 | **Step 3:** Define or import route components.
1101 | ```javacript
1102 | const Home = { template: '
Home
' }
1103 | const Services = { template: '
Services
' }
1104 | ```
1105 | **Step 4:** Define your route where each one maps to a component
1106 | ```javascript
1107 | const routes = [
1108 | { path: '/home', component: Home },
1109 | { path: '/services', component: Services }
1110 | ]
1111 | ```
1112 | **Step 5:** Create the router instance and pass the `routes` option
1113 | ```javascript
1114 | const router = new VueRouter({
1115 | routes // short for `routes: routes`
1116 | })
1117 | ```
1118 | **Step 6:** Create and mount the root instance.
1119 | ```javacript
1120 | const app = new Vue({
1121 | router
1122 | }).$mount('#app')
1123 | ```
1124 |
1125 | Now you are able to navigate different pages(Home, Services) with in Vue application.
1126 | 43. ### What is dynamic route matching?
1127 | Sometimes it may be required to map routes to the same component based on a pattern. Let's take a user component with the mapped URLs like `/user/john/post/123` and `/user/jack/post/235` using dynamic segments,
1128 | ```javascript
1129 | const User = {
1130 | template: '
User {{ $route.params.name }}, PostId: {{ route.params.postid }}
'
1131 | }
1132 |
1133 | const router = new VueRouter({
1134 | routes: [
1135 | // dynamic segments start with a colon
1136 | { path: '/user/:name/post/:postid', component: User }
1137 | ]
1138 | })
1139 | ```
1140 | 44. ### How to make router param changes as reactive?
1141 | When you navigate from one URL to other(mapped with a single component) using routes with params then the same component instance will be reused. Even though it is more efficient than destroying the old instance and then creating a new one, the lifecycle hooks of the component will not be called. This problem can be solved using either of the below approaches,
1142 | 1. Watch the $route object:
1143 | ```javascript
1144 | const User = {
1145 | template: '
User {{ $route.params.name }}
',
1146 | watch: {
1147 | '$route' (to, from) {
1148 | // react to route changes...
1149 | }
1150 | }
1151 | }
1152 | ```
1153 | 2. Use beforeRouteUpdate navigation guard: This is only available since 2.2 version.
1154 | ```javascript
1155 | const User = {
1156 | template: '
User {{ $route.params.name }}
',
1157 | beforeRouteUpdate (to, from, next) {
1158 | // react to route changes and then call next()
1159 | }
1160 | }
1161 | ```
1162 | Note that the beforeRouteEnter guard does NOT have access to `this`. Instead you can pass a callback to `next` to access the vm instance.
1163 | 45. ### What is route matching priority?
1164 | Sometimes the URL might be matched by multiple routes and the confusion of which route need to be mapped is resolved by route matching priority. The priority is based on order of routes configuration. i.e, The route which declared first has higher priority.
1165 | ```javascript
1166 | const router = new VueRouter({
1167 | routes: [
1168 | // dynamic segments start with a colon
1169 | { path: '/user/:name', component: User } // This route gets higher priority
1170 | { path: '/user/:name', component: Admin }
1171 | { path: '/user/:name', component: Customer }
1172 | ]
1173 | })
1174 | ```
1175 | 46. ### What are nested routes?
1176 | Generally, the app is composed of nested components which are nested multiple levels deep. The segments of a URL corresponds to a certain structure of these nested components. To render components into the nested outlet, you need to use the `children` option in `VueRouter` constructor config.
1177 | Let's take a user app composed of profile and posts nested components with respective routes. You can also define a default route configuration when there is no matching nested route.
1178 | ```javascript
1179 | const router = new VueRouter({
1180 | routes: [
1181 | { path: '/user/:id', component: User,
1182 | children: [
1183 | {
1184 | // UserProfile will be rendered inside User's when /user/:id/profile is matched
1185 | path: 'profile',
1186 | component: UserProfile
1187 | },
1188 | {
1189 | // UserPosts will be rendered inside User's when /user/:id/posts is matched
1190 | path: 'posts',
1191 | component: UserPosts
1192 | },
1193 | // UserHome will be rendered inside User's when /user/:id is matched
1194 | { path: '',
1195 | component: UserHome },
1196 | ]
1197 | }
1198 | ]
1199 | })
1200 | ```
1201 | 47. ### What are single file components?
1202 | Single File Components are an easy concept to understand. Earlier you might heard about all three parts(HTML, JavaScript and CSS) of your application kept in different components. But Single File Components encapsulate the structure, styling and behaviour into one file. In the beginning, it seems strange to have all three parts in one file, but it actually makes a lot more sense.
1203 | Let's take an example of Singile File Components
1204 | ```javascript
1205 |
1206 |
1207 |
Welcome {{ name }}!
1208 |
1209 |
1210 |
1211 |
1220 |
1221 |
1227 | ```
1228 | 48. ### Is Single File Components violating separation of concerns?
1229 | As for the latest modern UI development, separation of concerns is not equal to separation of file types. So it is preferred to divide codebase layers into loosely-coupled components and compose them instead of dividing the codebase into three huge layers that interweave with one another. This way makes Single File Components more cohesive and maintainable by combining template, logic and styles together inside a component.
1230 | You can also still maintain javascript and CSS files separately with hot-reloading and pre-compilation features. For example,
1231 | ```
1232 |
1233 |
This section will be pre-compiled and hot reloaded
1234 |
1235 |
1236 |
1237 | ```
1238 | 49. ### What are the problems solved by Single File Components?
1239 | The Single File Components solve the common problems occurred in a javascript driven application with a .vue extension. The list of issues are,
1240 | 1. Global definitions force unique names for every component
1241 | 2. String templates lack syntax highlighting and require ugly slashes for multiline HTML
1242 | 3. No CSS support means that while HTML and JavaScript are modularized into components, CSS is conspicuously left out
1243 | 4. No build step restricts us to HTML and ES5 JavaScript, rather than preprocessors like Pug (formerly Jade) and Babel
1244 | 50. ### What are filters?
1245 | Filters can be used to apply common text formatting. These Filters should be appended to the end of the JavaScript expression, denoted by the “pipe” symbol. You can use them in two specific cases:
1246 | 1. mustache interpolations
1247 | 2. v-bind expressions
1248 |
1249 | For example, Let's define a local filter named capitalize in a component’s options
1250 | ```javascript
1251 | filters: {
1252 | capitalize: function (value) {
1253 | if (!value) return ''
1254 | value = value.toString()
1255 | return value.charAt(0).toUpperCase() + value.slice(1)
1256 | }
1257 | }
1258 | ```
1259 | Now you can use the filter in either mustache interpolation or v-bind expression,
1260 | ```javascript
1261 |
1262 | {{ username | capitalize }}
1263 |
1264 |
1265 |
1266 | ```
1267 | 51. ### What are the different ways to create filters?
1268 | You can define filters in two ways,
1269 | 1. **Local filters:**
1270 | You can define local filters in a component’s options. In this case, filter is applicable to that specific component.
1271 | ```javascript
1272 | filters: {
1273 | capitalize: function (value) {
1274 | if (!value) return ''
1275 | value = value.toString()
1276 | return value.charAt(0).toUpperCase() + value.slice(1)
1277 | }
1278 | }
1279 | ```
1280 | 2. **Global filters:**
1281 | You can also define a filter globally before creating the Vue instance. In this case, filter is applicable to all the components with in the vue instance,
1282 | ```javascript
1283 | Vue.filter('capitalize', function (value) {
1284 | if (!value) return ''
1285 | value = value.toString()
1286 | return value.charAt(0).toUpperCase() + value.slice(1)
1287 | })
1288 |
1289 | new Vue({
1290 | // ...
1291 | })
1292 | ```
1293 | 52. ### How do you chain filters?
1294 | You can chain filters one after the other to perform multiple manipulations on the expression. The generic structure of filter chain would be as below,
1295 | ```javascript
1296 | {{ message | filterA | filterB | filterB ... }}
1297 | ```
1298 | In the above chain stack, you can observe that message expression applied with three filters, each separated by a pipe(|) symbol. The first filter(filterA) takes the expression as a single argument and the result of the expression becomes an argument for second filter(filterB) and the chain continue for remaining filters.
1299 | For example, if you want to transform date expression with a full date format and uppercase then you can apply dateFormat and uppercase filters as below,
1300 | ```javascript
1301 | {{ birthday | dateFormat | uppercase }}
1302 | ```
1303 |
1304 | 53. ### Is it possible to pass parameters for filters?
1305 | Yes, you can pass arguments for a filter similar to a javascript function. The generic structure of filter parameters would be as follows,
1306 | ```javascript
1307 | {{ message | filterA('arg1', arg2) }}
1308 | ```
1309 | In this case, filterA takes message expression as first argument and the explicit parameters mentioned in the filter as second and third arguments.
1310 | For example, you can find the exponential strength of a particular value
1311 | ```javascript
1312 | {{ 2 | exponentialStrength(10) }} // prints 2 power 10 = 1024
1313 | ```
1314 | 54. ### What are plugins and their various services?
1315 |
1316 | Plugins provides global-level functionality to Vue application. The plugins provide various services,
1317 | 1. Add some global methods or properties. For example, vue-custom-element
1318 | 2. Add one or more global assets (directives, filters and transitions). For example, vue-touch
1319 | 3. Add some component options by global mixin. For example, vue-router
1320 | 4. Add some Vue instance methods by attaching them to Vue.prototype.
1321 | 5. A library that provides an API of its own, while at the same time injecting some combination of the above. For example, vue-router
1322 | 55. ### How to create a plugin?
1323 | The Plugin is created by exposing an `install` method which takes Vue constructor as a first argument along with options. The structure of VueJS plugin with possible functionality would be as follows,
1324 | ```javascript
1325 | MyPlugin.install = function (Vue, options) {
1326 | // 1. add global method or property
1327 | Vue.myGlobalMethod = function () {
1328 | // some logic ...
1329 | }
1330 |
1331 | // 2. add a global asset
1332 | Vue.directive('my-directive', {
1333 | bind (el, binding, vnode, oldVnode) {
1334 | // some logic ...
1335 | }
1336 | ...
1337 | })
1338 |
1339 | // 3. inject some component options
1340 | Vue.mixin({
1341 | created: function () {
1342 | // some logic ...
1343 | }
1344 | ...
1345 | })
1346 |
1347 | // 4. add an instance method
1348 | Vue.prototype.$myMethod = function (methodOptions) {
1349 | // some logic ...
1350 | }
1351 | }
1352 | ```
1353 | 56. ### How to use a plugin?
1354 | You can use plugin by passing your plugin to Vue's **use** global method. You need to apply this method before start your app by calling new Vue().
1355 | ```javascript
1356 | // calls `MyPlugin.install(Vue, { someOption: true })`
1357 | Vue.use(MyPlugin)
1358 |
1359 | new Vue({
1360 | //... options
1361 | })
1362 | ```
1363 | 57. ### What are mixins?
1364 | Mixin gives us a way to distribute reusable functionalities in Vue components. These reusable functions are merged with existing functions. A mixin object can contain any component options. Let us take an example of mixin with `created` lifecycle which can be shared across components,
1365 | ```javascript
1366 | const myMixin = {
1367 | created(){
1368 | console.log("Welcome to Mixins!")
1369 | }
1370 | }
1371 | var app = new Vue({
1372 | el: '#root',
1373 | mixins: [myMixin]
1374 | })
1375 | ```
1376 | **Note:** Multiple mixins can be specified in the mixin array of the component.
1377 | 58. ### What are global mixins?
1378 | Sometimes there is a need to extend the functionality of Vue or apply an option to all Vue components available in our application. In this case, mixins can be applied globally to affect all components in Vue. These mixins are called as global mixins. Let's take an example of global mixin,
1379 | ```javascript
1380 | Vue.mixin({
1381 | created(){
1382 | console.log("Write global mixins")
1383 | }
1384 | })
1385 |
1386 | new Vue({
1387 | el: '#app'
1388 | })
1389 | ```
1390 | In the above global mixin, the mixin options spread across all components with the console running during the instance creation. These are useful during test, and debugging or third party libraries. At the same time, You need to use these global mixins sparsely and carefully, because it affects every single Vue instance created, including third party components.
1391 | 59. ### How do you use mixins in CLI?
1392 | Using Vue CLI, mixins can be specified anywhere in the project folder but preferably within `/src/mixins` for ease of access. Once these mixins are created in a `.js` file and exposed with the `export` keyword, they can be imported in any component with the `import` keyword and their file paths.
1393 | 60. ### What are the merging strategies in mixins?
1394 | When a mixin and the component itself contain overlapping options, the options will be merged based on some strategies.
1395 | 1. The data objects undergo a recursive merge, with the component’s data taking priority over mixins in cases of overlapping or conflicts.
1396 | ```javascript
1397 | var mixin = {
1398 | data: function () {
1399 | return {
1400 | message: 'Hello, this is a Mixin'
1401 | }
1402 | }
1403 | }
1404 | new Vue({
1405 | mixins: [mixin],
1406 | data: function () {
1407 | return {
1408 | message: 'Hello, this is a Component'
1409 | }
1410 | },
1411 | created: function () {
1412 | console.log(this.$data); // => { message: "Hello, this is a Component'" }
1413 | }
1414 | })
1415 | ```
1416 | 2. The Hook functions which are overlapping merged into an array so that all of them will be called. Mixin hooks will be called before the component’s own hooks.
1417 | ```javascript
1418 | const myMixin = {
1419 | created(){
1420 | console.log("Called from Mixin")
1421 | }
1422 | }
1423 |
1424 | new Vue({
1425 | el: '#root',
1426 | mixins:[myMixin],
1427 | created(){
1428 | console.log("Called from Component")
1429 | }
1430 | })
1431 |
1432 | //Called from Mixin
1433 | //Called from Component
1434 | ```
1435 | 3. The options that expect object values(such as methods, components and directives) will be merged into the same object. In this case, the component’s options will take priority when there are conflicting keys in these objects.
1436 | ```javascript
1437 | var mixin = {
1438 | methods: {
1439 | firstName: function () {
1440 | console.log('John')
1441 | },
1442 | contact: function () {
1443 | console.log('+65 99898987')
1444 | }
1445 | }
1446 | }
1447 |
1448 | var vm = new Vue({
1449 | mixins: [mixin],
1450 | methods: {
1451 | lastName: function () {
1452 | console.log('Murray')
1453 | },
1454 | contact: function () {
1455 | console.log('+91 893839389')
1456 | }
1457 | }
1458 | })
1459 |
1460 | vm.firstName() // "John"
1461 | vm.lastName() // "Murray"
1462 | vm.contact() // "+91 893839389"
1463 | ```
1464 | 61. ### What are custom options merging strategies?
1465 | Vue uses the default strategy which overwrites the existing value while custom options are merged. But if you want a custom option merged using custom login then you need to attach a function to `Vue.config.optionMergeStrategies`
1466 | For the example, the structure of `myOptions` custom option would be as below,
1467 | ```javascript
1468 | Vue.config.optionMergeStrategies.myOption = function (toVal, fromVal) {
1469 | // return mergedVal
1470 | }
1471 | ```
1472 | Let's take below Vuex 1.0 merging strategy as an advanced example,
1473 | ```javascript
1474 | const merge = Vue.config.optionMergeStrategies.computed
1475 | Vue.config.optionMergeStrategies.vuex = function (toVal, fromVal) {
1476 | if (!toVal) return fromVal
1477 | if (!fromVal) return toVal
1478 | return {
1479 | getters: merge(toVal.getters, fromVal.getters),
1480 | state: merge(toVal.state, fromVal.state),
1481 | actions: merge(toVal.actions, fromVal.actions)
1482 | }
1483 | }
1484 | ```
1485 | 62. ### What are custom directives?
1486 | Custom Directives are tiny commands that you can attach to DOM elements. They are prefixed with v- to let the library know you're using a special bit of markup and to keep syntax consistent. They are typically useful if you need low-level access to an HTML element to control a bit of behavior. Let's create a custom focus directive to provide focus on specific form element during page load time,
1487 | ```javascript
1488 | // Register a global custom directive called `v-focus`
1489 | Vue.directive('focus', {
1490 | // When the bound element is inserted into the DOM...
1491 | inserted: function (el) {
1492 | // Focus the element
1493 | el.focus()
1494 | }
1495 | })
1496 | ```
1497 | Now you can use v-focus directive on any element as below,
1498 | ```html
1499 |
1500 | ```
1501 | 63. ### How do you register directives locally?
1502 | You can also register directives locally(apart from globally) using directives option in component as below,
1503 | ```javascript
1504 | directives: {
1505 | focus: {
1506 | // directive definition
1507 | inserted: function (el) {
1508 | el.focus()
1509 | }
1510 | }
1511 | }
1512 | ```
1513 | Now you can use v-focus directive on any element as below,
1514 | ```html
1515 |
1516 | ```
1517 | 64. ### What are the hook functions provided by directives?
1518 | A directive object can provide several hook functions,
1519 | 1. bind: This occurs once the directive is attached to the element.
1520 | 2. inserted: This hook occurs once the element is inserted into the parent DOM.
1521 | 3. update: This hook is called when the element updates, but children haven't been updated yet.
1522 | 4. componentUpdated: This hook is called once the component and the children have been updated.
1523 | 5. unbind: This hook is called only once when the directive is removed.
1524 |
1525 | **Note:** There are several arguments that can be passed to the above hooks.
1526 | 65. ### What are the directive Hook Arguments?
1527 | All the hooks have `el`, `binding`, and `vnode` as arguments. Along with that, **update** and **componentUpdated** hooks expose `oldVnode`, to differentiate between the older value passed and the newer value. Below are the arguments passed to the hooks,
1528 | 1. `el`: The element the directive is bound to and it can be used to directly manipulate the DOM.
1529 | 2. `binding`: An object containing the following properties.
1530 | 1. `name`: The name of the directive, without the `v-` prefix.
1531 | 2. `value`: The value passed to the directive. For example in `v-my-directive="1 + 1"`, the value would be 2.
1532 | 3. `oldValue`: The previous value, only available in update and componentUpdated. It is available whether or not the value has changed.
1533 | 4. `expression`: The expression of the binding as a string. For example in `v-my-directive="1 + 1"`, the expression would be "1 + 1".
1534 | 5. `arg`: The argument passed to the directive, if any. For example in v-my-directive:foo, the arg would be "foo".
1535 | 6. `modifiers`: An object containing modifiers, if any. For example in v-my-directive.foo.bar, the modifiers object would be `{ foo: true, bar: true }`.
1536 | 3. `vnode`: The virtual node produced by Vue’s compiler.
1537 | 4. `oldVnode`: The previous virtual node, only available in the update and componentUpdated hooks.
1538 |
1539 | The arguments can be represented diagrammatically across the hooks as below,
1540 | 
1541 | 66. ### How do you pass multiple values to a directive?
1542 | A directive can take any valid javascript expression. So if you want to pass multiple values then you can pass in a JavaScript object literal.
1543 | Let's pass object literal to an avatar directive as below
1544 | ```html
1545 |
1546 | ```
1547 | Now let us configure avatar directive globally,
1548 | ```javascript
1549 | Vue.directive('avatar', function (el, binding) {
1550 | console.log(binding.value.width) // 500
1551 | console.log(binding.value.height) // 400
1552 | console.log(binding.value.url) // path/logo
1553 | console.log(binding.value.text) // "Iron Man"
1554 | })
1555 | ```
1556 | 67. ### What is function shorthand in directive hooks?
1557 | In few cases, you may want the same behavior on `bind` and `update` hooks irrespective of other hooks. In this situation you can use function shorthand,
1558 | ```javascript
1559 | Vue.directive('theme-switcher', function (el, binding) {
1560 | el.style.backgroundColor = binding.value
1561 | })
1562 | ```
1563 | 68. ### What is the benefit of render functions over templates?
1564 | In VueJS, the templates are very powerful and recommended to build HTML as part of your application. However, some of the special cases like dynamic component creation based on input or slot value can be achieved through render functions. Also, these functions gives the full programmatic power of javascript eco system.
1565 | 69. ### What is a render function?
1566 | Render function is a normal function which receives a `createElement` method as it’s first argument used to create virtual nodes. Internally Vue.js' templates actually compile down to render functions at build time. Hence templates are just syntactic sugar of render functions. Let's take an example of simple Div markup and corresponding render function,
1567 | The HTML markup can be written in template tag as below,
1568 | ```javascript
1569 |
1570 |
1571 |
Welcome to Vue render functions
1572 |
1573 |
1574 | ```
1575 | and the compiled down or explicit render function would appear as below,
1576 | ```javascript
1577 | render: function (createElement) {
1578 | return createElement('div', {
1579 | 'class': {
1580 | 'is-rounded': this.isRounded
1581 | }
1582 | }, [
1583 | createElement('p', 'Welcome to Vue render functions')
1584 | ]);
1585 | },
1586 | ```
1587 | **Note:** The react components are built with render functions in JSX.
1588 | 70. ### Explain the structure of createElement with arguments?
1589 | The createElement accepts few arguments to use all the template features. Let us see the basic structure of createElement with possible arguments,
1590 | ```javascript
1591 | // @returns {VNode}
1592 | createElement(
1593 | // An HTML tag name, component options, or async function resolving to one of these.
1594 | // Type is {String | Object | Function}
1595 | // Required.
1596 | 'div',
1597 |
1598 | // A data object corresponding to the attributes you would use in a template.
1599 | //Type is {Object}
1600 | // Optional.
1601 | {
1602 | // Normal HTML attributes
1603 | attrs: {
1604 | id: 'someId'
1605 | },
1606 | // Component props
1607 | props: {
1608 | myProp: 'somePropValue'
1609 | },
1610 | // DOM properties
1611 | domProps: {
1612 | innerHTML: 'This is some text'
1613 | },
1614 | // Event handlers are nested under `on`
1615 | on: {
1616 | click: this.clickHandler
1617 | },
1618 | // Similar to `v-bind:style`, accepting either a string, object, or array of objects.
1619 | style: {
1620 | color: 'red',
1621 | fontSize: '14px'
1622 | },
1623 | //Similar to `v-bind:class`, accepting either a string, object, or array of strings and objects.
1624 | class: {
1625 | classsName1: true,
1626 | classsName2: false
1627 | },
1628 | ....
1629 | },
1630 |
1631 | // Children VNodes, built using `createElement()`, or using strings to get 'text VNodes'.
1632 | // Type is {String | Array}
1633 | // Optional.
1634 | [
1635 | 'Learn about createElement arguments.',
1636 | createElement('h1', 'Headline as a child virtual node'),
1637 | createElement(MyComponent, {
1638 | props: {
1639 | someProp: 'This is a prop value'
1640 | }
1641 | })
1642 | ]
1643 | )
1644 | ```
1645 | see details of the date object in official [doc](https://vuejs.org/v2/guide/render-function.html#The-Data-Object-In-Depth).
1646 | 71. ### How can you write duplicate virtual nodes in a component?
1647 | All virtual nodes(VNodes) in the component tree must be unique.i.e, You can't write duplicated nodes in a straightforward way. If you want to duplicate the same element/component many times then you should use factory function.
1648 | The below render function is invalid where you are trying to duplicate h1 element 3 times,
1649 | ```javascript
1650 | render: function (createElement) {
1651 | var myHeadingVNode = createElement('h1', 'This is a Virtual Node')
1652 | return createElement('div', [
1653 | myHeadingVNode, myHeadingVNode, myHeadingVNode
1654 | ])
1655 | }
1656 | ```
1657 | You can make duplicates with factory function,
1658 | ```javascript
1659 | render: function (createElement) {
1660 | return createElement('div',
1661 | Array.apply(null, { length: 3 }).map(function () {
1662 | return createElement('h1', 'This is a Virtual Node')
1663 | })
1664 | )
1665 | }
1666 | ```
1667 | 72. ### List down the template equivalents in render functions?
1668 | VueJS provides proprietary alternatives and plain javascript usage for the template features. Let's list down them in a table for comparision,
1669 |
1670 | | Templates | Render function |
1671 | |---- | --------- |
1672 | | Conditional and looping directives: v-if and v-for | Use JavaScript’s if/else and map concepts|
1673 | | Two-way binding: v-model | Apply own JS logic with value binding and event binding |
1674 | | Capture Event modifiers: .passive, .capture, .once and .capture.once or .once.capture| &, !, ~ and ~! |
1675 | | Event and key modifiers: .stop, .prevent, .self, keys(.enter, .13) and Modifiers Keys(.ctrl, .alt, .shift, .meta) | Use javascript solutions: event.stopPropagation(), event.preventDefault(), if (event.target !== event.currentTarget) return, if (event.keyCode !== 13) return and if (!event.ctrlKey) return |
1676 | | Slots: slot attributes | Render functions provide this.$slots and this.$scopedSlots instance properties|
1677 | 73. ### What are functional components?
1678 | The functional components are just simple functions to create simple components just by passing a context. Every functional component follows two rules,
1679 | 1. **Stateless:** It doesn’t keep any state by itself
1680 | 2. **Instanceless:** It has no instance, thus no this
1681 |
1682 | You need to define `functional: true` to make it functional. Let's take an example of functional components,
1683 | ```javascript
1684 | Vue.component('my-component', {
1685 | functional: true,
1686 | // Props are optional
1687 | props: {
1688 | // ...
1689 | },
1690 | // To compensate for the lack of an instance,
1691 | // we are now provided a 2nd context argument.
1692 | render: function (createElement, context) {
1693 | // ...
1694 | }
1695 | })
1696 | ```
1697 | **Note:** The functional components are quite popular in React community too.
1698 | 74. ### What are the similarities between VueJS and ReactJS?
1699 | Even though ReactJS and VueJS are two different frameworks there are few similarities(apart from the common goal of utilized in interface design) between them.
1700 | 1. Both frameworks are based on the **Virtual DOM** model
1701 | 2. They provide features such Component-based structure and reactivity
1702 | 3. They are intended for working with the root library, while all the additional tasks are transferred to other libraries(routing, state management etc).
1703 | 75. ### What is the difference between VueJS and ReactJS?
1704 | Even though VueJS and ReactJS share few common features there are many difference between them. Let's list down them in a table format.
1705 |
1706 | | Feature | VueJS | ReactJS |
1707 | |---- | --------- | ---- |
1708 | | Type | JavaScript MVC Framework | JavaScript Library |
1709 | | Platform | Primarily focused on web development | Both Web and Native |
1710 | | Learning Curve | A steep learning curve and requires deep knowledge | A steep learning curve and requires deep knowledge |
1711 | | Simplicity | Vue is simpler than React | React is more complex than Vue |
1712 | | Bootstrap Application | Vue-cli | CRA (Create React App) |
1713 | 76. ### What are the advantages of VueJS over ReactJS?
1714 | Vue has the following advantages over React
1715 | 1. Vue is smaller and faster
1716 | 2. The convenient templates ease the process of developing
1717 | 3. It has simpler javascript syntax without learning JSX
1718 | 77. ### What are the advantages of ReactJS over VueJS?
1719 | React has the following advantages over Vue
1720 | 1. ReactJS gives more flexibility in large apps developing
1721 | 2. Easy to test
1722 | 3. Well-suited for mobile apps creation
1723 | 4. The eco system is quite big and well matured.
1724 | 78. ### What are the differences between VueJS and AngularJS?
1725 | The the syntax of Vue and Angular is common at some points because Angular is the basis for VueJS development in the beginning. But there are many differences between VueJS and Angular as listed,
1726 |
1727 | | Feature | VueJS | AngularJS |
1728 | |---- | --------- | ---- |
1729 | | Complexity | Easy to learn, simple API and design | The framework is bit huge and need some learning curve on typescript etc |
1730 | | Binding of Data | One-way binding | Two-way binding |
1731 | | Learning Curve | A steep learning curve and requires deep knowledge | A steep learning curve and requires deep knowledge |
1732 | | Founders | Created by Former Google Employee | Powered by Google |
1733 | | Initial Release | February 2014 | September 2016 |
1734 | | Model | Based on Virtual DOM(Document Object Model) | Based on MVC(Model-View-Controller) |
1735 | | Written in | JavaScript | TypeScript |
1736 | 79. ### What are dynamic components?
1737 | The dynamic component is used to dynamically switch beetween multiple components using **** element and pass data to v-bind:is attribute.
1738 | Let's create a dynamic component to switch between different pages of a website,
1739 | ```javascript
1740 | new Vue({
1741 | el: '#app',
1742 | data: {
1743 | currentPage: 'home'
1744 | },
1745 | components: {
1746 | home: {
1747 | template: "
Home
"
1748 | },
1749 | about: {
1750 | template: "
About
"
1751 | },
1752 | contact: {
1753 | template: "
Contact
"
1754 | }
1755 | }
1756 | })
1757 | ```
1758 | Now you can use the dynamic component which holds the current page,
1759 | ```html
1760 |
1761 |
1762 |
1763 |
1764 |
1765 |
1766 | ```
1767 | 80. ### What is the purpose of keep alive tag?
1768 | Keep-alive tag is an abstract component used to preserve component state or avoid re-rendering. When you wrapped tag around a dynamic component, it caches the inactive component instances without destroying them.
1769 | Let's see the example usage of it,
1770 | ```javascript
1771 |
1772 |
1773 |
1774 |
1775 | ```
1776 | When there are multiple conditional children, it requires that only one child is rendered at a time.
1777 |
1778 | ```javascript
1779 |
1780 |
1781 |
1782 |
1783 |
1784 | ```
1785 | **Note:** Remember that keep-alive tag doesn’t render a DOM element itself, and doesn’t show up in the component parent chain.
1786 | 81. ### What are async components?
1787 | In large applications, we may need to divide the app into smaller chunks and only load a component from the server when it’s needed. To make this happen, Vue allows you to define your component as a factory function that asynchronously resolves your component definition. These components are known as async component.
1788 | Let's see an example of async component using webpack code-splitting feature,
1789 | ```javascript
1790 | Vue.component('async-webpack-example', function (resolve, reject) {
1791 | // Webpack automatically split your built code into bundles which are loaded over Ajax requests.
1792 | require(['./my-async-component'], resolve)
1793 | })
1794 | ```
1795 | Vue will only trigger the factory function when the component needs to be rendered and will cache the result for future re-renders
1796 | 82. ### What is the structure of async component factory?
1797 | Async component factory is useful to resolve the component asynchronously. The async component factory can return an object of the below format.
1798 | ```javascript
1799 | const AsyncComponent = () => ({
1800 | // The component to load (should be a Promise)
1801 | component: import('./MyComponent.vue'),
1802 | // A component to use while the async component is loading
1803 | loading: LoadingComponent,
1804 | // A component to use if the load fails
1805 | error: ErrorComponent,
1806 | // Delay before showing the loading component. Default: 200ms.
1807 | delay: 200,
1808 | // The error component will be displayed if a timeout is
1809 | // provided and exceeded. Default: Infinity.
1810 | timeout: 3000
1811 | })
1812 | ```
1813 | 83. ### What are inline templates?
1814 | If you keep an `inline-template` on a child component then it will use its inner content as a template instead of treating as reusable independent content.
1815 | ```javascript
1816 |
1817 |
1818 |
Inline templates
1819 |
Treated as component component owne content
1820 |
1821 |
1822 | ```
1823 | **Note:** Even though this inline-templates gives more flexibility for template authoring, it is recommended to define template using template property or tag inside .vue component.
1824 |
1825 | 84. ### What are X Templates?
1826 | Apart from regular templates and inline templates, you can also define templates using a script element with the type `text/x-template` and then referencing the template by an id.
1827 | Let's create a x-template for simple use case as below,
1828 | ```javascript
1829 |
1832 | ```
1833 | Now you can define the template using reference id,
1834 | ```javascript
1835 | Vue.component('x-template-example', {
1836 | template: '#script-template'
1837 | })
1838 | ```
1839 |
1840 | 85. ### What are recursive components?
1841 | The Components that can recursively invoke themselves in their own template are known as recursive components.
1842 | ```javascript
1843 | Vue.component('recursive-component', {
1844 | template: `
1845 | `
1846 | });
1847 | ```
1848 | Recursive components are useful for displaying comments on a blog, nested menus, or basically anything where the parent and child are the same, eventhough with different content.
1849 |
1850 | **Note:** Remember that recursive component can lead infinite loops with `max stack size exceeded` error, so make sure recursive invocation is conditional(for example, v-if directive).
1851 |
1852 | 86. ### How do you resolve circular dependencies between components?
1853 | In complex applications, vue components will actually be each other’s descendent and ancestor in the render tree. Let's say componentA and componentB included in their respective templates which makes circular dependency,
1854 | ```javascript
1855 | //ComponentA
1856 |
1865 | ```
1866 | This can be solved by either registering(or wait until) the child component in `beforeCreate` hook or using webpack's asynchronous import while registering the component,
1867 |
1868 | **Solution1:**
1869 | ```javascript
1870 | beforeCreate: function () {
1871 | this.$options.components.componentB = require('./component-b.vue').default
1872 | }
1873 | ```
1874 | **Solution2:**
1875 | ```javascript
1876 | components: {
1877 | componentB: () => import('./component-b.vue')
1878 | }
1879 | ```
1880 | 87. ### How do you make sure vue application is CSP complaint?
1881 |
1882 | Some environments(Google Chrome Apps) prohibits the usage of `new Function()` for evaluating expressions and the full builds of vue applications depends on this feature to compile templates. Due to this reason, the full builds of VueJS application are not CSP complaint. In this case you can use **runtime-only** builds with Webpack + vue-loader or Browserify + vueify technology stack through which templates will be precompiled into render functions. This way you can make sure VueJS applications are 100% CSP complaint.
1883 |
1884 | 88. ### What is the difference between full and runtime only builds?
1885 |
1886 | There are two types of builds provided by VueJS,
1887 |
1888 | **1. Full:** These are the builds that contain both the compiler and the runtime.
1889 |
1890 | **2. Runtime Only:** These builds doesn't include compiler but the code is responsible for creating Vue instances, rendering and patching virtual DOM. These are about 6KB lighter min+gzip.
1891 |
1892 | 89. ### List down different builds of vuejs?
1893 | Below are the list of different builds of VueJS based on type of build,
1894 |
1895 | | Type | UMD | CommonJS | ES Module (for bundlers) | ES Module (for browsers) |
1896 | |---- | --------- | ---- | ---- | --- |
1897 | | Full | vue.js | vue.common.js | vue.esm.js | vue.esm.browser.js |
1898 | | Runtime only | vue.runtime.js | vue.runtime.common.js | vue.runtime.esm.js | NA |
1899 | | Full (production) | vue.min.js | NA | NA | vue.esm.browser.min.js |
1900 | | Runtime-only (production) | vue.runtime.min.js | NA | NA | NA |
1901 |
1902 | 90. ### How do you configure vuejs in webpack?
1903 | You can configure vueJS in webpack using alias as below,
1904 |
1905 | ```javascript
1906 | module.exports = {
1907 | // ...
1908 | resolve: {
1909 | alias: {
1910 | 'vue$': 'vue/dist/vue.esm.js' // 'vue/dist/vue.common.js' for webpack 1
1911 | }
1912 | }
1913 | }
1914 | ```
1915 | 91. ### What is the purpose of vuejs compiler?
1916 | The compiler is is responsible for compiling template strings into JavaScript render functions. For example, the below code snippet shows the difference of templates which need compiler and not,
1917 | ```javascript
1918 | // this requires the compiler
1919 | new Vue({
1920 | template: '
{{ message }}
'
1921 | })
1922 |
1923 | // this does not
1924 | new Vue({
1925 | render (h) {
1926 | return h('div', this.message)
1927 | }
1928 | })
1929 | ```
1930 | 92. ### What is Dev Tools and its purpose?
1931 | DevTools is a browser extension allowing you to inspect and debug your Vue applications in a more user-friendly interface. You can find the below extensions for different browsers or environments,
1932 | 1. Chrome Extension
1933 | 2. Firefox Addon
1934 | 3. Standalone Electron app (works with any environment)
1935 |
1936 | The DevTools plugins can be used as shown in the below snapshot,
1937 |
1938 |
1939 |
1940 | **Note:**
1941 | 1. If the page uses a production/minified build of Vue.js, devtools inspection is disabled by default so the Vue pane won't show up.
1942 | 2. To make it work for pages opened via `file://` protocol, you need to check "Allow access to file URLs" for this extension in Chrome's extension management panel.
1943 | 93. ### What is the browser support of VueJS?
1944 | It supports all ECMAScript5 complaint browsers as mentioned in this [url](https://caniuse.com/#feat=es5). VueJS doesn't support IE8 browser and below, because it uses ECMAScript 5 features that are un-shimmable(require support from the underlying JS engine) in IE8.
1945 | 94. ### How do you use various CDNs?
1946 | VueJS is available in jsdelivr, unpkg and cdnjs etc CDNs. Normally you can use them for prototyping or learning purposes. For example, you can use them using jsdelivr with latest versions as below,
1947 | ```javascript
1948 |
1949 | ```
1950 | You can use it for native ES modules as below,
1951 | ```javascript
1952 |
1955 | ```
1956 |
1957 | **Note:** You can remove version number to get latest version.
1958 | 95. ### How do you force update?
1959 | It is extremely rare situation of having to manually force an update despite the fact that no reactive data has changed. i.e, To force the Vue instance to re-render manually. You can do it force update using **vm.$forceUpdate()** API method.
1960 |
1961 | **Note:** It does not affect all child components but only the instance itself and child components with inserted slot content.
1962 | 96. ### What is the purpose of vuejs once directive?
1963 | If you want to render `a lot of static content` then you need to make sure it only evaluated once and then cached thereafter. In this case, you can use `v-once` directive by wrapping at the root level. The example usage of v-once directive would be as below,
1964 | ```javascript
1965 | Vue.component('legal-terms', {
1966 | template: `
1967 |
1968 |
Legal Terms
1969 | ... a lot of static content goes here...
1970 |
1971 | `
1972 | })
1973 | ```
1974 |
1975 | **Note:** It is recommended not to overuse unless there is slow rendering due to lot of static content.
1976 | 97. ### How do you access the root instance?
1977 | The root instance(new Vue()) can be accessed with the `$root` property. Let's see the usage of root instance with an example. First let's create a root instance with properties and methods as below,
1978 | ```javascript
1979 | // The root Vue instance
1980 | new Vue({
1981 | data: {
1982 | age: 26
1983 | },
1984 | computed: {
1985 | fullName: function () { /* ... */ }
1986 | },
1987 | methods: {
1988 | interest: function () { /* ... */ }
1989 | }
1990 | })
1991 | ```
1992 | Now you can access root instance data and it's methods with in subcomponents as below,
1993 | ```javascript
1994 | // Get root data
1995 | this.$root.age
1996 |
1997 | // Set root data
1998 | this.$root.age = 29
1999 |
2000 | // Access root computed properties
2001 | this.$root.fullName
2002 |
2003 | // Call root methods
2004 | this.$root.interest()
2005 | ```
2006 | It is recommend using Vuex to manage state instead of using root instance as a global store.
2007 | 98. ### List out top 10 organizations using Vuejs?
2008 | Below are the top 10 organizations using VueJS for their applications or products,
2009 |
2010 | 1. Facebook - Used on marketing side of its Newsfeed
2011 | 2. Netflix - Used in two internal apps for building movie streaming interfaces
2012 | 3. Adobe - Used for Portfolio, a custom website builder designed to help users showcase their creative work
2013 | 4. Xiaomi - Used for products where it sells from consumer electronics to software
2014 | 5. Alibaba - Provide their apps an excellent experience to its customers
2015 | 6. WizzAir - A budget airline WizzAir used for their customers user interface
2016 | 7. EuroNews
2017 | 8. Laracasts
2018 | 9. GitLab
2019 | 10. Laracasts
2020 |
2021 | 99. ### What is the purpose of renderError?
2022 | When the default render function encounters an error then you can use rennderError as an alternative render output. The error will be passed to renderError as the second argument. The example usage of renderError is as below,
2023 | ```javacript
2024 | new Vue({
2025 | render (h) {
2026 | throw new Error('An error')
2027 | },
2028 | renderError (h, err) {
2029 | return h('div', { style: { color: 'red' }}, err.stack)
2030 | }
2031 | }).$mount('#app')
2032 | ```
2033 | 100. ### How do you access parent instance?
2034 | The $parent object refers to the **immediate outer scope**. The parent will be accessible as `this.$parent` for the child, and the child will be pushed into the parent’s $children array. It establishes a parent-child relationship between the two instances(parent and child). You can access parent data and properties similar to $root.
2035 | 101. ### What is vuex?
2036 | Vuex is a state management pattern + library (Flux-inspired Application Architecture) for Vue.js applications. It serves as a centralized store for all the components in an application, with rules ensuring that the state can only be mutated in a predictable fashion.
2037 | 102. ### What are the major components of State Management Pattern?
2038 | The state management has state, view and actions as major components. The pattern followed by these components in a application is known as State Management Pattern. Below are the components in a detail,
2039 | 1. The **state**, which is the source of truth that drives our app
2040 | 2. The **view**, which is just a declarative mapping of the state
2041 | 3. The **actions**, which are the possible ways the state could change in reaction to user inputs from the view.
2042 | Let us take a counter example which follows state management pattern with the above 3 components,
2043 | ```javascript
2044 | new Vue({
2045 | // state
2046 | data () {
2047 | return {
2048 | count: 0
2049 | }
2050 | },
2051 | // view
2052 | template: `
2053 |
{{ count }}
2054 | `,
2055 | // actions
2056 | methods: {
2057 | increment () {
2058 | this.count++
2059 | }
2060 | }
2061 | })
2062 | ```
2063 | 103. ### How do you represent one way data flow in vuex?
2064 | Vue.js has a one-way data flow model, through the props property. The same concept can be represented in vuex has below,
2065 |
2066 | 104. ### What is a vuejs loader?
2067 | Vue loader is a loader for webpack that allows you to author Vue components in a format called Single-File Components (SFCs). For example, it authors HelloWorld component in a SFC,
2068 | ```javascript
2069 |
2070 |
{{ message }}
2071 |
2072 |
2073 |
2082 |
2083 |
2088 | ```
2089 | 105. ### How do you configure vue loader in webpack?
2090 | Vue Loader's configuration is a bit different from other loaders by adding Vue Loader's plugin to your webpack config. The vue loader plugin is required for cloning any other rules(js and css rules) defined and applying them to the corresponding language blocks(
2204 |
2209 | ```
2210 | //child.vue
2211 | ```javascript
2212 |
2213 |
2214 |
child
2215 |
2216 |
2217 |
2218 |
2223 |
2228 | ```
2229 | Now the background color of child wrapper is going to be blue instead red.
2230 | 112. ### How do you style dynamic generated content using scoped css?
2231 | The scoped css style doesn't impact v-html directive's dynamically generated content. In this case, you can use deep selectors to solve this styling issue.
2232 | 113. ### Is CSS modules supported in Vuejs?
2233 | Yes, vue-loader provides first-class integration with CSS Modules as an alternative for simulated scoped CSS.
2234 | 114. ### Can I use runtime builds for all templates?
2235 | No, templates (or any Vue-specific HTML) are ONLY allowed in .vue files and render functions are required in other cases.
2236 | 115. ### How to use CSS modules in vuejs?
2237 | Below are the steps to use css modules in VueJS,
2238 | 1. ** Enable CSS modules:** CSS Modules must be enabled by passing modules: true option to css-loader
2239 | ```javascript
2240 | // webpack.config.js
2241 | {
2242 | module: {
2243 | rules: [
2244 | // ... other rules omitted
2245 | {
2246 | test: /\.css$/,
2247 | use: [
2248 | 'vue-style-loader',
2249 | {
2250 | loader: 'css-loader',
2251 | options: {
2252 | // enable CSS Modules
2253 | modules: true,
2254 | // customize generated class names
2255 | localIdentName: '[local]_[hash:base64:8]'
2256 | }
2257 | }
2258 | ]
2259 | }
2260 | ]
2261 | }
2262 | }
2263 | ```
2264 | 2. ** Add module attribute:** Add the module attribute to your `
2271 | ```
2272 | 3. ** Inject CSS modules:** You can inject CSS modules object with computed property $style
2273 | ```javascript
2274 |
2275 |
2276 | Background color should be in blue
2277 |
2278 |
2279 | ```
2280 | It can work with object/array syntax of :class binding.
2281 | 116. ### Can I use CSS modules for preprocessors?
2282 | Yes,You can use preprocessors with CSS Modules. For example, sass-loader can configured in webpack file for sass preprocessor.
2283 | ```javascript
2284 | // webpack.config.js -> module.rules
2285 | {
2286 | test: /\.scss$/,
2287 | use: [
2288 | 'vue-style-loader',
2289 | {
2290 | loader: 'css-loader',
2291 | options: { modules: true }
2292 | },
2293 | 'sass-loader'
2294 | ]
2295 | }
2296 | ```
2297 | 117. ### Is it possible to use custom inject name for CSS modules?
2298 | You can customize the name of the injected computed property by giving the module attribute a value. This will be helpful to avoid overwriting injected styled if you have more than one
2303 |
2304 |
2307 | ```
2308 | 118. ### What is hot reloading in vue loader?
2309 | Hot reloading is not about reloading the page when you edit any .vue file. Instead, when you edit a *.vue file, all instances of that component will be swapped in without reloading the page. It improves the development experience when you are tweaking the templates or styling of your components.
2310 | 119. ### What is the default behavior of hot reloading?
2311 | Hot Reload is always enabled except below situations:
2312 |
2313 | 1. webpack target is node (SSR)
2314 | 2. webpack minifies the code
2315 | 3. process.env.NODE_ENV === 'production'
2316 | 120. ### How do you disable hot reloading explicitly?
2317 | You can use `hotReload: false` option to disable the Hot Reload explicitly. It can be configured as below,
2318 | ```javascript
2319 | module: {
2320 | rules: [
2321 | {
2322 | test: /\.vue$/,
2323 | loader: 'vue-loader',
2324 | options: {
2325 | hotReload: false // disables Hot Reload
2326 | }
2327 | }
2328 | ]
2329 | }
2330 | ```
2331 | 121. ### How do you use hot reloading?
2332 | The vue loader plugin internally uses hot reloading. If you are scaffolding project with `vue-cli`, hot reloading comes out of the box but if you are manually setting up the project then hot reloading is enabled by default with `webpack-dev-server --hot` command.
2333 | 122. ### What are state preservation rules in hot reloading?
2334 | Below are the state preservation rules in hot reloading,
2335 | 1.When editing the `` of a component, instances of the edited component will re-render in place, preserving all current private state.
2336 | 2.When editing the `
2737 |
2738 | ```
2739 | **Note:** You can use a specific version/tag via URLs like https://unpkg.com/vuex@2.0.0. If you don't mention any version then it will point to latest version.
2740 | 148. ### Do I need promise for vuex?
2741 | Yes, Vuex requires Promise. If your supporting browsers do not implement Promise (e.g. IE), you can use a polyfill library, such as es6-promise using npm or yarn.
2742 | ```javascript
2743 | npm install es6-promise --save # NPM
2744 | yarn add es6-promise # Yarn
2745 | ```
2746 | After that import into anywhere in your application,
2747 | ```javascript
2748 | import 'es6-promise/auto'
2749 | ```
2750 | 149. ### How do you display store state in vue components?
2751 | Since Vuex stores are reactive, you can retrieve" state from store by simply returning store's state from within a computed property. i.e, Whenever store state changes, it will cause the computed property to re-evaluate, and trigger associated DOM updates.
2752 | Let's take a hello word component which display store's state in the template,
2753 | ```javascript
2754 | // let's create a hello world component
2755 | const Greeting = {
2756 | template: `
{{ greet }}
`,
2757 | computed: {
2758 | greet () {
2759 | return store.state.msg
2760 | }
2761 | }
2762 | }
2763 | ```
2764 | 150. ### How do you inject store into child components?
2765 | Vuex provides a mechanism to "inject" the store into all child components from the root component with the store option. It will be enabled by vue.use(vuex).
2766 | For example, let's inject into our app component as below,
2767 | ```javascript
2768 | const app = new Vue({
2769 | el: '#app',
2770 | // provide the store using the "store" option.
2771 | // this will inject the store instance to all child components.
2772 | store,
2773 | components: { Greeting },
2774 | template: `
2775 |
2776 |
2777 |
2778 | `
2779 | })
2780 | ```
2781 | Now the store will be injected into all child components of the root and will be available on them as **this.$store**
2782 | ```javascript
2783 | // let's create a hello world component
2784 | const Greeting = {
2785 | template: `
{{ greet }}
`,
2786 | computed: {
2787 | greet () {
2788 | return this.$store.state.msg
2789 | }
2790 | }
2791 | }
2792 | ```
2793 | 151. ### What is mapState helper?
2794 | In Vuex application, creating a computed property every time whenever we want to access the store's state property or getter is going to be repetitive and verbose, especially if a component needs more than one state property. In this case, we can make use of the mapState helper of vuex which generates computed getter functions for us.
2795 | Let's take an increment example to demonstrate mapState helper,
2796 | ```javascript
2797 | // in full builds helpers are exposed as Vuex.mapState
2798 | import { mapState } from 'vuex'
2799 |
2800 | export default {
2801 | // ...
2802 | computed: mapState({
2803 | // arrow functions can make the code very succinct!
2804 | username: state => state.username,
2805 |
2806 | // passing the string value 'username' is same as `state => state.username`
2807 | usernameAlias: 'username',
2808 |
2809 | // to access local state with `this`, a normal function must be used
2810 | greeting (state) {
2811 | return this.localTitle + state.username
2812 | }
2813 | })
2814 | }
2815 | ```
2816 | We can also pass a string array to mapState when the name of a mapped computed property is the same as a state sub tree name
2817 | ```javascript
2818 | computed: mapState([
2819 | // map this.username to store.state.username
2820 | 'username'
2821 | ])
2822 | ```
2823 | 152. ### How do you combine local computed properties with mapState helper?
2824 | You can use object spread operator syntax in order to combine mapState helper(which returns an object) with other local computed properties. This way it simplify merging techniques using utilities.
2825 | ```javascript
2826 | computed: {
2827 | localComputed () { /* ... */ },
2828 | // mix this into the outer object with the object spread operator
2829 | ...mapState({
2830 | // ...
2831 | })
2832 | }
2833 | ```
2834 | 153. ### Do you need to replace entire local state with vuex?
2835 | No, if a piece of state strictly belongs to a single component, it could be just fine leaving it as local state. i.e, Eventhough vuex used in the application, it doesn't mean that you need to keep all the local state in vuex store. Other the code becomes more verbose and indirect although it makes your state mutations more explicit and debuggable.
2836 | 154. ### What are vuex getters??
2837 | Vuex getters acts as computed properties for stores to compute derived state based on store state. Similar to computed properties, a getter's result is cached based on its dependencies, and will only re-evaluate when some of its dependencies have changed.
2838 | Let's take a todo example which as completedTodos getter to find all completed todos,
2839 | ```javascript
2840 | const store = new Vuex.Store({
2841 | state: {
2842 | todos: [
2843 | { id: 1, text: 'Vue course', completed: true },
2844 | { id: 2, text: 'Vuex course', completed: false },
2845 | { id: 2, text: 'Vue Router course', completed: true }
2846 | ]
2847 | },
2848 | getters: {
2849 | completedTodos: state => {
2850 | return state.todos.filter(todo => todo.completed)
2851 | }
2852 | }
2853 | })
2854 | ```
2855 | **Note:**Getters receive state as first argument.
2856 | 155. ### What is a property style access?
2857 | You can access values of store's getter object(store.getters) as properties. This is known as property style access.
2858 | For example, you can access todo's status as a property,
2859 | ```javascript
2860 | store.getters.todosStatus
2861 | ```
2862 | The getters can be passed as 2nd argument for other getters. For example, you can derive completed todo's count based on their status as below,
2863 | ```javascript
2864 | getters: {
2865 | completedTodosCount: (state, getters) => {
2866 | return getters.todosStatus === 'completed'
2867 | }
2868 | }
2869 | ```
2870 | **Note:** The getters accessed as properties are cached as part of Vue's reactivity system.
2871 | 156. ### What is a method style access?
2872 | You can access store's state in a method style by passing arguments. For example, you can pass user id to find user profile information as below,
2873 | ```javascript
2874 | getters: {
2875 | getUserProfileById: (state) => (id) => {
2876 | return state.users.find(user => user.id === id)
2877 | }
2878 | }
2879 | ```
2880 | After that you can access it as a method call,
2881 | ```javascript
2882 | store.getters.getUserProfileById(111); {id: '111', name: 'John', age: 33}
2883 | ```
2884 | 157. ### What is mapGetter helper??
2885 | The mapGetters is a helper that simply maps store getters to local computed properties. For example, the usage of getters for todo app would be as below,
2886 | ```javascript
2887 | import { mapGetters } from 'vuex'
2888 |
2889 | export default {
2890 | computed: {
2891 | // mix the getters into computed with object spread operator
2892 | ...mapGetters([
2893 | 'completedTodos',
2894 | 'todosCount',
2895 | // ...
2896 | ])
2897 | }
2898 | }
2899 | ```
2900 | 158. ### What are mutations?
2901 | Vuex mutations are similar to any events with a string `type` and a `handler`. The handler function is where we perform actual state modifications, and it will receive the state as the first argument.
2902 | For example, the counter example with increment mutation would be as below,
2903 | ```javascript
2904 | const store = new Vuex.Store({
2905 | state: {
2906 | count: 0
2907 | },
2908 | mutations: {
2909 | increment (state) {
2910 | // mutate state
2911 | state.count++
2912 | }
2913 | }
2914 | })
2915 | ```
2916 | You can't directly invoke mutation instead you need to call `store.commit` with its type. The above mutation would be triggered as folows
2917 | ```javascript
2918 | store.commit('increment')
2919 | ```
2920 | 159. ### How do you commit with payload?
2921 | You can also pass **payload** for the mutation as an additional argument to `store.commit`. For example, the counter mutation with payload object would be as below,
2922 | ```javascript
2923 | mutations: {
2924 | increment (state, payload) {
2925 | state.count += payload.increment
2926 | }
2927 | }
2928 | ```
2929 | And then you can trigger increment commit
2930 | ```javascript
2931 | store.commit('increment', {
2932 | increment: 20
2933 | })
2934 | ```
2935 | **Note:** You can also pass primitives as payload.
2936 | 160. ### What is object style commit?
2937 | You can also commit a mutation is by directly using an object that has a **type** property.
2938 | ```javascript
2939 | store.commit({
2940 | type: 'increment',
2941 | value: 20
2942 | })
2943 | ```
2944 | Now the entire object will be passed as the payload to mutation handlers(i.e, without any changes to handler signature).
2945 | ```javascript
2946 | mutations: {
2947 | increment (state, payload) {
2948 | state.count += payload.value
2949 | }
2950 | }
2951 | ```
2952 | 161. ### What are the caveats with vuex mutations?
2953 | Since a Vuex store's state is made reactive by Vue, the same reactivity caveats of vue will apply to vuex mutations. These are the rules should be followed for vuex mutations,
2954 | 1. It is recommended to initialize store's initial state with all desired fields upfront
2955 | 2. Add new properties to state Object either by set method or object spread syntax
2956 | ```javascript
2957 | Vue.set(stateObject, 'newProperty', 'John')
2958 | ```
2959 | (OR)
2960 | ```javascript
2961 | state.stateObject = { ...state.stateObject, newProperty: 'John' }
2962 | ```
2963 | 162. ### Why mutations should be synchronous?
2964 | You need to remember that mutation handler functions must be synchronous. This is why because any state mutation performed in the callback is essentially un-trackable. It is going to be problematic when the devtool will need to capture a "before" and "after" snapshots of the state during the mutations.
2965 | ```javascript
2966 | mutations: {
2967 | someMutation (state) {
2968 | api.callAsyncMethod(() => {
2969 | state.count++
2970 | })
2971 | }
2972 | }
2973 | ```
2974 | 163. ### How do you perform mutations in components?
2975 | You can commit mutations in components with either **this.$store.commit('mutation name')** or mapMutations helper to map component methods to **store.commit** calls.
2976 | For example, the usage of mapMutations helper on counter example would be as below,
2977 | ```javascript
2978 | import { mapMutations } from 'vuex'
2979 |
2980 | export default {
2981 | methods: {
2982 | ...mapMutations([
2983 | 'increment', // map `this.increment()` to `this.$store.commit('increment')`
2984 |
2985 | // `mapMutations` also supports payloads:
2986 | 'incrementBy' // map `this.incrementBy(amount)` to `this.$store.commit('incrementBy', amount)`
2987 | ]),
2988 | ...mapMutations({
2989 | add: 'increment' // map `this.add()` to `this.$store.commit('increment')`
2990 | })
2991 | }
2992 | }
2993 | ```
2994 | 164. ### Is it mandatory to use constants for mutation types?
2995 | No, it is not mandatory. But you might observed that State management implementations such Flux and Redux use constants for mutation types. This convention is just a preference and useful to take advantage of tooling like linters, and putting all constants in a single file allows your collaborators to get an at-a-glance view of what mutations are possible in the entire application.
2996 | For example, the mutations can be declared as below,
2997 | ```javascript
2998 | // mutation-types.js
2999 | export const SOME_MUTATION = 'SOME_MUTATION'
3000 | ```
3001 | And you can configure them in store as follows,
3002 | ```javascript
3003 | // store.js
3004 | import Vuex from 'vuex'
3005 | import { SOME_MUTATION } from './mutation-types'
3006 |
3007 | const store = new Vuex.Store({
3008 | state: { ... },
3009 | mutations: {
3010 | // ES2015 computed property name feature to use a constant as the function name
3011 | [SOME_MUTATION] (state) {
3012 | // mutate state
3013 | }
3014 | }
3015 | })
3016 | ```
3017 | 165. ### How do you perform asynchronous operations?
3018 | In Vuex, mutations are synchronous transactions. But if you want to handle asynchronous operations then you should use **actions**.
3019 | 166. ### What are differences between mutations and actions?
3020 | Actions are similar to mutations, but there are two main differences,
3021 | 1. Mutations perform mutations on the state, actions commit mutations.
3022 | 2. Actions can contain arbitrary asynchronous operations unlike mutations.
3023 | 167. ### Give an example usage of actions?
3024 | Vuex provides actions property similar mutations property in order to define action handlers. These action handlers receive context object as an argument which has same properties and methods of store instance.
3025 | Let's see counter example to demonstrate increment action which commits respective mutation,
3026 | ```javascript
3027 | const store = new Vuex.Store({
3028 | state: {
3029 | count: 0
3030 | },
3031 | mutations: {
3032 | increment (state) {
3033 | state.count++
3034 | }
3035 | },
3036 | actions: {
3037 | increment (context) {
3038 | context.commit('increment')
3039 | }
3040 | }
3041 | })
3042 | ```
3043 | 168. ### How do you dispatch actions?
3044 | Actions are simply triggered with the store.dispatch method as below,
3045 | ```javascript
3046 | store.dispatch('increment')
3047 | ```
3048 | 169. ### Can you dispatch an action using payload or object style?
3049 | Yes, actions support both payload and object style format similar to mutations.
3050 | ```javascript
3051 | // dispatch with a payload
3052 | store.dispatch('incrementAsync', {
3053 | amount: 10
3054 | })
3055 |
3056 | // dispatch with an object
3057 | store.dispatch({
3058 | type: 'incrementAsync',
3059 | amount: 10
3060 | })
3061 | ```
3062 | 170. ### Can I use styled components in vuejs?
3063 | Styled components is basically used for ReactJS applications. If you want to use for VueJS applications, there is vuejs styled components library available under styled component library. VueJS Styled component is a javascript library for stying vuejs applications.
3064 | 171. ### How do you dispatch actions in components?
3065 | You can dispatch actions in components with **this.$store.dispatch('action name')**, or use the **mapActions** helper which maps component methods to store.dispatch calls.
3066 | For example, you can dispatch increment actions in counter component as below,
3067 | ```javascript
3068 | import { mapActions } from 'vuex'
3069 |
3070 | export default {
3071 | // ...
3072 | methods: {
3073 | ...mapActions([
3074 | 'increment', // map `this.increment()` to `this.$store.dispatch('increment')`
3075 |
3076 | // `mapActions` also supports payloads:
3077 | 'incrementBy' // map `this.incrementBy(amount)` to `this.$store.dispatch('incrementBy', amount)`
3078 | ]),
3079 | ...mapActions({
3080 | add: 'increment' // map `this.add()` to `this.$store.dispatch('increment')`
3081 | })
3082 | }
3083 | }
3084 | ```
3085 | 172. ### How do you compose actions?
3086 | You can write multiple actions together to handle more complex async flows either by chaining promises or async/await. i.e, `store.dispatch` can handle Promise returned by the triggered action handler and it also returns Promise.
3087 | Let's take two actions to see how they are combined and handled async flows,
3088 | ```javascript
3089 | actions: {
3090 | actionOne ({ commit }) {
3091 | return new Promise((resolve, reject) => {
3092 | setTimeout(() => {
3093 | commit('first mutation')
3094 | resolve()
3095 | }, 1000)
3096 | })
3097 | },
3098 | actionTwo ({ dispatch, commit }) {
3099 | return dispatch('actionA').then(() => {
3100 | commit('second mutation')
3101 | })
3102 | }
3103 | }
3104 | ```
3105 | As per the above example, When you try to dispatch actionTwo it dispatchs actionOne first and then commits respective mutation. You can still simplify with async/await as below,
3106 | ```javascript
3107 | actions: {
3108 | async actionOne ({ commit }) {
3109 | commit('first mutation', await getDataAsPromise())
3110 | },
3111 | async actionTwo ({ dispatch, commit }) {
3112 | await dispatch('actionOne') // wait for `actionA` to finish
3113 | commit('second mutation', await getSomeDataAsPromise())
3114 | }
3115 | }
3116 | ```
3117 | 173. ### What are modules in vuex?
3118 | If you keep all state of our application in a single big state, the store can get really bloated. To solve this problem, Vuex allows us to divide our store into modules. Here, each module can contain its own state, mutations, actions, getters, and even nested modules.
3119 | Let's take an example with multiple modules, configuring them in vuex and accessing different modules,
3120 | ```javascript
3121 | const moduleA = {
3122 | state: { ... },
3123 | mutations: { ... },
3124 | actions: { ... },
3125 | getters: { ... }
3126 | }
3127 |
3128 | const moduleB = {
3129 | state: { ... },
3130 | mutations: { ... },
3131 | actions: { ... },
3132 | getters: { ... }
3133 | }
3134 |
3135 | const store = new Vuex.Store({
3136 | modules: {
3137 | a: moduleA,
3138 | b: moduleB
3139 | }
3140 | })
3141 |
3142 | store.state.a // -> `moduleA`'s state
3143 | store.state.b // -> `moduleB`'s state
3144 | ```
3145 | 174. ### What is module local state?
3146 | When you use modules the local state will be available to mutations, getters and actions in different ways.
3147 | 1. Both mutations and getters will receive module local state as first argument.
3148 | ```javascript
3149 | const moduleOne = {
3150 | state: { count: 0 },
3151 | mutations: {
3152 | increment (state) {
3153 | state.count++; // Here state refers local module state
3154 | }
3155 | },
3156 |
3157 | getters: {
3158 | average (state) {
3159 | return state.count / 2
3160 | }
3161 | }
3162 | }
3163 | ```
3164 | 2. In actions, local state will be available as first argument.
3165 | ```javascript
3166 | const moduleOne = {
3167 | actions: {
3168 | incrementConditional ({ state, commit, rootState }) {
3169 | if (state.count < rootState.count) {
3170 | commit('increment')
3171 | }
3172 | }
3173 | }
3174 | }
3175 | ```
3176 | 175. ### What is namespacing in vuex?
3177 |
--------------------------------------------------------------------------------
/images/DevTools.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/magisters-cc/vuejs-interview-questions-russian/ef2b7215468b4294c7bab6af5e267e047ce71942/images/DevTools.png
--------------------------------------------------------------------------------
/images/custom-directives.svg:
--------------------------------------------------------------------------------
1 |
360 |
--------------------------------------------------------------------------------
/images/flow.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/magisters-cc/vuejs-interview-questions-russian/ef2b7215468b4294c7bab6af5e267e047ce71942/images/flow.png
--------------------------------------------------------------------------------
/images/vuelifecycle.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/magisters-cc/vuejs-interview-questions-russian/ef2b7215468b4294c7bab6af5e267e047ce71942/images/vuelifecycle.png
--------------------------------------------------------------------------------
/images/vuex-app-structure.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/magisters-cc/vuejs-interview-questions-russian/ef2b7215468b4294c7bab6af5e267e047ce71942/images/vuex-app-structure.png
--------------------------------------------------------------------------------