InterviewSolution
This section includes InterviewSolutions, each offering curated multiple-choice questions to sharpen your knowledge and support exam preparation. Choose a topic below to get started.
| 1. |
<script> export default { data() { return { author: { name: 'John Doe', books: [ 'Vue 2 - Advanced Guide', 'Vue 3 - Basic Guide', 'Vue 4 - The Mystery' ] } } }, computed: { publishedBooksMessage() { return this.author.books.length > 0 ? 'Yes' : 'No' } } } </script> <template> <p>Has published books:</p> <span>{{ publishedBooksMessage }}</span> </template> |
|
Answer» The state is an important part of Vue applications SINCE it is concerned with how data is passed among components.
State management is better:
|
|
| 2. |
Second: |
Answer»
Example: tracking the position of some moving object, as the time passes if something is in motion then its position is changing. so, we can say the position has a different state and a logic performing some manipulation on position is called stateful logic.
Generally stateless logic does not involve a RECORD of previous interactions and each and every interaction request has to be handled based on information that is new (that comes with the request). |
|
| 3. |
<script> export default { data() { return { author: { name: 'John Doe', books: [ 'Vue 2 - Advanced Guide', 'Vue 3 - Basic Guide', 'Vue 4 - The Mystery' ] } } }, methods: { publishedBooksMessage() { return this.author.books.length > 0 ? 'Yes' : 'No' } } } </script> <template> <p>Has published books:</p> <span>{{ publishedBooksMessage() }}</span> </template> |
|
Answer» //FancyButton template <template> <button class="fancy-btn"> <slot/> </button> </template> <style> .fancy-btn { border-radius: 8px; } </style> //Parent template <script> import FancyButton from './FancyButton.vue' export default { components: { FancyButton} } </script> <template> <FancyButton> <span> CLICK me! </span> </FancyButton> </template> >> Output he slot has similar usage with PROPS as it is down-way passing but it is used to pass a template fragment to a child component, and let the child component render the fragment it received within its own template rather than passing data. So, in the above code ‘<slot/>’ represents the content (template fragment) to be passed by the parent. Therefore, the ‘click me!’ text is what is to be replaced by the slot tag. As for changing the color of the text from the parent FALLTHROUGH ATTRIBUTE is used. Here the attribute is the style and the value of the attribute will be ’red’ assignment to the color attribute as shown below. <FancyButton> <span style="color:red">Click me! </span> </FancyButton>>> Output |
|
| 4. |
First: |
Answer»
What MAKES the fallthrough attributes unique is -
Example <!-- template of <Button1> --> <BUTTON>click here</button> <Button1 class="large" /> //included in another component <!-- final render of template of <Button1> after fallthrough attribute --> <button class="large">click here</button> |
|
| 5. |
The following two codes have the same output which is ‘yes’. Which one is more preferable performance-wise and why? |
|
Answer» The Parent component <script> import Child from './Child.VUE' export default { components: { Child }, MOUNTED() { this.$refs.child } } </script> <template> <Child ref="child" /> </template>The Child component export default { EXPOSE: ['dataTwo', 'methodOne'], data() { return { dataOne: 'foo', dataTwo: 'bar' } }, methods: { MethodOne() { /* ... */ }, MethodTwo() { /* ... */ } } }The two properties that are FULLY accessible to the parent are 'dataTwo', 'methodOne' (those which are listed in the expose option). Since the other two properties of the child (‘dataOne’, ‘methodTwo’) are not included in the expose option, they will not be accessible to the parent component which is referencing the child. ref is one of Vue’s special attributes which allows us to obtain a specific DOM object’s direct reference or the instance of the child component after it is mounted. In our case, it references the instance of the child component which allows the parent component to access all of its properties unless the expose option is used in the child component. The parent component would have full access to all properties of the child if the expose option was not used since ‘ref’ ATTRIBUTE is referencing the instance of the child component. Therefore the expose option is what limits the other properties from being accessed by the parent component. |
|
| 6. |
Explain the dissimilarity between one-way data flow and two-way data binding? Which vue.js directive is used for each? |
|
Answer» The second one is preferable performance-wise since it uses the computed property. Computed property :
|
|
| 7. |
Why should arrow functions not be used in writing lifecycle hooks in Vue instances? |
Answer»
|
|
| 8. |
Explain Vue.js common issues when tracking changes? |
|
Answer» The most common lifecycle hooks are mounted, UPDATED, and unmounted. All lifecycle hooks are called with their ‘this’ context pointing to the current active INSTANCE invoking it. Arrow functions are not independent, and as a result, they cannot DEFINE a ‘this’ of their own. But arrow functions are bound to their parent’s function’s context. The Arrow function (=>), when used in the Vue app, the Arrow function (=>), the keyword ‘this’ does not bind to the Vue instance, resulting in errors. HENCE it is advised to use the standard function declaration instead of the arrow function, as shown below. export default { mounted() { console.log(`the component is now mounted.`) } } |
|
| 9. |
const router = new VueRouter({ routes: [ { path: '/user/:name', component: User } { path: '/user/:name', component: Admin } { path: '/user/:name', component: Customer } ] }) |
|
Answer» All properties defined in Vue instances are reactive. It means that the components are automatically updated and re-rendered in case of changes at any instance. All these properties will change to getters and setters in the initialization stage. Following setbacks should be considered while designing a Vue app; JavaScript LIMITATIONS: Vue cannot detect the deletion or addition of an object property. Vue performs the getter/setter CONVERSION process during instance initialization; property must be PRESENT in the data object for Vue to convert it and make it reactive. Example: VAR vm = new Vue({ data: { a: 1 } }) // `vm.a` is now reactive vm.b = 2 // `vm.b` is NOT reactiveAdditionally, it cannot detect the modification of array items. Vue does not ALLOW adding new root-level reactive properties to a created instance. It is feasible to add reactive properties to a nested object using the Vue.set(object, propertyName, value) method, as shown below. Vue.set(vm.someObject, 'b', 2) |
|
| 10. |
Does the following code have any errors? If yes, what is the error and how are you supposed to correct it? If not, which component (User,Admin,Customer) is going to be invoked when ‘/user/:name’ is navigated to. |
|
Answer» No, the code does not have any error, but SOMETIMES the URL might be matched by multiple routes, and the CONFUSION of which path needs to be MAPPED can be resolved by route matching priority. The priority is based on the ORDER of route configuration. i.e., The route which is declared first has higher priority.
|
|
| 11. |
What is the data flow heeded by props, and what are the possible solutions for mutation cases? |
|
Answer» All props follow a ONE-way-down binding between the child's property and the PARENT one. i.e., when the parent property is updated, that latest prop value will be passed down to the child, but not the other way(child to parent, which is carried out by emitting events rather than using props). The child component should not mutate the prop defined in the parent; otherwise, it throws a warning in the console. The possible mutation cases can be solved in the ways illustrated below. The possible mutation cases are:
The solution for this mutation case is defining a local property in the child component and assigning the parent value as the initial value. The following code snippet clarifies the solution. props: ['defaultUser'],
The solution for this mutation case is defining a computed property using the prop's value. Computed properties are ANOTHER powerful feature from Vue that allows us to transform or perform calculations on our data and easily REUSE the result as an up-to-date variable in our template. Below is the illustration of computed properties to mutate the parent's prop props: ['environment'], computed: { localEnvironment: function () { return this.environment.trim().toUpperCase() } } |
|
| 12. |
What are Components in Vue.js? Show how to create one inside a Vue instance. |
|
Answer» In Vue.js component
Steps to create a Vue component called ‘ComponentOne’ INSIDE the Vue instance. Step 1: Create the component by defining a COMMON element of the UI(User interface) to be displayed. Save the file with name ComponentFirst.vue <template> <div><h1>This is coming from component First</h1></div> </template>The component consists of an h1 tag nested in div tag to print ‘This is coming from component First’ at the size of heading one. Step 2: Define the vue instance in which the component is imported (included) <script> import ComponentOne from './ComponentFirst.vue' export default { components: { ComponentFirst } </script> <template> < h1 >Here is the reused component!</h1> <ComponentFirst /> <ComponentFirst /> </template>>> Output
|
|
| 13. |
What will the output of the following code be and why? |
|
Answer» <script> export default { data() { return { someObject: {} } }, methods:{ print(){ const newObject = {} this.someObject = newObject console.log(newObject === this.someObject)} }, mounted() { this.print(); } } </script> >> Output False. The Vue JavaScript framework is "reactive," which can automatically refresh your data. Reactivity is when changes in the application state are automatically reflected in the DOM (DOCUMENT Object Model), a programming API for HTML and XML documents. In this case, we have a Proxy object (in our case someObject) that ENABLES us to create a proxy for another object (in our case newObject), which can intercept and redefine fundamental operations for that object. When this.someObject object is accessed, the value is a reactive proxy of the original newObject. The original newObject is left unchanged and will not be made reactive. The use of Proxy does introduce a new CAUTION to be aware of: the proxied object(someObject) is not equal to the original object(newObject) in terms of identity comparison (===).That is why the actual output is false rather than true, EVEN if the value assigned to each object is the same. |
|
| 14. |
Based on the code below, when would the value for ‘answer’ instance compute either yes or no? Which Vue.js feature is used for initiating the action? |
|
Answer» <script> export default { data() { return { question: '', answer: 'Questions mostly contain question mark' } }, watch: { question(newQuestion, oldQuestion) { if (newQuestion.indexOf('?') > -1) { this.getAnswer() } } }, methods: { async getAnswer() { this.answer = 'Thinking...' try { const res = await fetch('https://yesno.wtf/api') this.answer = (await res.json()).answer } catch (e) { this.answer = 'Error! Could not reach the API. ' + error } } } } </script> <template> <p> Ask a yes/no question: <input v-model="question" /> </p> <p>{{ answer }}</p> </template>
Defining watch, the FUNCTION that prevents the modification in the state should have the same NAME as the reactive instance. In this case, it is observed that the function name has two parameters (newQuestion, oldQuestion) . If the function's name DIFFERS from the reactive instance, nothing will happen to the value of the 'answer' even if the question is modified and the question mark is included. |
|
| 15. |
Explain what are detection mutation methods and array detection non-mutation methods? List three array detection mutation methods and two array detection non-mutation methods with their uses? |
|
Answer» Mutation methods ALTER the original array. Following are the list of array mutation methods that initiate VIEW updates
Below are the methods that don't mutate the original array but return a new array and are CALLED non-mutation methods.
|
|
| 16. |
What do we use to pass data from child component to parent component and how (specify the steps required)? |
|
Answer» Values go up from child to parent using the $EMIT() event. Step 01: Invoke the $emit() method in the child to send a piece of the data to its parent component. //ChildComponent.vue <template> <button @click="$emit('name', 'RAJESH Bhagia')">click me</button> </template>The first statement in the $emit method is the event name, and the second ARGUMENT is the actual data to be passed to the parent component. Step 02: Use the same event name prefixed with the @ symbol to define the child component inside the template in the parent component. Its VALUE will be a function, and it will have the actual value RETURNED in its argument. STEP 03: Declare the getName function inside the methods objects with an argument //ParentComponent.vue <script> import ChildComponent from './ChildComponent.vue' export default { components: { ChildComponent }, methods:{ getName(value) {//Step 03 console.log(value); } } } </script> <template> <h3>Below is the child component within the parent component!</h3> <ChildComponent @name="getName"/> //STEP 02 </template> The value passed to the getName function is the one assigned on the ChildComponent which is “Rajesh Bhagia”.So it is the one which is passed to the parent component by emitting an event. >> Output after button click in child component >> Rajesh Bhagia |
|
| 17. |
What is the mounted event in Vue.js? |
Answer»
|
|
| 18. |
What are local filters? |
Answer»
|
|
| 19. |
What is two-way data binding? Which directive is used for the two-way data binding? |
Answer»
When the VALUE in the input field changes ‘message’ in the p tag automatically updates. |
|
| 20. |
What is the v-show directive? Show with a simple example code. |
Answer»
An element with a v-show which is ‘h1’ will always be rendered and remain in the DOM; v-show only toggles the display CSS property of the element. Example for V-show <div id="app"> <div v-show="showText"> <p>Show the first nice text</p> </div> <div v-show="!showText"> <p>Show the second bad text</p> </div> <button v-on:CLICK="showText = !showText">Toggle texts</button> </div> NEW Vue({ el: "#app", data: { showText: TRUE, } })Result:
|
|
| 21. |
What are the drawbacks of mixins? |
|
Answer» Mixin is a Vue.js feature that allows code reusability between components in Vue.js application instances and a software composition tool. The drawback of MIXINS:
|
|
| 22. |
Which lifecycle hook plays a great role for memory leak not to occur? |
|
Answer» A memory leak occurs when memory is allocated for use and not deallocated where the memory area is no longer needed. It is caused by a PROGRAM that does not deallocate (free up) the extra memory allocated and FREQUENT memory leaks might halt everything.
Example: mounted() { this.chart = new PowerGraph(); }When the component is mounted the third-party library is created so it has to be destroyed in the beforeDestroy() lifecycle hook for memory leak not to occur as shown below. beforeDestroy() { this.chart.destroy(); }If the clean-up is not done before our component gets destroyed, then that memory is never going to be RELEASED. Hence, a memory leak occurs. |
|
| 23. |
What do we mean by stateless logic? Give an example. |
Answer»
GENERALLY stateless logic does not involve a record of previous interactions and every interaction request has to be handled based on new information (that comes with the request). |
|
| 24. |
What is a one-way data flow? |
Answer»
|
|
| 25. |
Explain what reactivity is in Vue.js. |
Answer»
|
|
| 26. |
The splice() method has several uses. Specify what type of array detection method it is and list at least two from its usage. |
Answer»
|
|
| 27. |
What causes prop drilling in Vue.js? |
Answer»
|
|
| 28. |
What is the name of a logic which involves managing the state which changes over time? Give an example. |
Answer»
Example: TRACKING the position of some moving object, as the time passes if something is in motion then its position is changing. So we can say the position has a different state and a logic performing MANIPULATION on the position is called stateful logic. // eventBus.jsimport Vue from 'vue'export const bus = new Vue()// component_one.vueimport { bus } from './eventBus.js'export default { data() { RETURN { value: null } } methodcreated() {// Listens for the 'action' eventbus.$on('action', ({ payload }) => { this.value = payload })}}// component_two.vueimport {bus} from './eventBus.js'export default {created() {// Emits the 'action' eventbus.$emit('action', {myPayload: 45678})}} |
|
| 29. |
What are the uses of computed properties in Vue.js? |
|
Answer» A computed property is one of the powerful features from Vue that enables US to transform our data by performing calculations on the VALUE of the data and then easily REUSING the result as an up-to-date variable in our template. Computed properties have the FOLLOWING usage:
|
|
| 30. |
What are fallthrough attributes in Vue.js? |
|
Answer» Fallthrough attributes are v-on event listeners or attributes which are passed to other components implicitly. This means it does not involve the EXPLICIT declaration of the attribute or event in the receiving component’s props (from parent to child) or emit (from child to parent). We do not have to EXPLICITLY specify what is to be inherited in the inheriting component rather the attribute or the event passed will apply to the component without specifying its declaration in its component <!-- TEMPLATE of <Button1> --> <button>click here</button> <Button1 CLASS="large" /> //included in another component <!-- final render of template of <Button1> after fallthrough attribute --> <button class="large">click here</button> |
|
| 31. |
What is the use of the push() method on the array? |
Answer»
|
|
| 32. |
What are Vue.js Watchers? In which case do we use them? |
Answer»
|
|
| 33. |
What is state management in Vue.js and which library is commonly used in Vue for state management? |
|
Answer» The state is an important part of Vue applications since it is concerned with how data is passed among components.
|
|
| 34. |
How do we create a Vue.js instance? Write the code. |
|
Answer» In VUE.js application must always start with the creation of a new instance which is created USING the Vue function as shown below. // code for CREATING vm Vue.js instance var vm = new Vue( { // OPTIONS } )Options indicate a PLACE where we include different options to be included in the Vue instance when it is first created. |
|
| 35. |
What are props in Vue.js? |
|
Answer» Props - is an option in the parent component to list what properties of the child are to be accessed by the parent. So, it is down-WAY referencing unlike emit which is used in up-way binding from parent to child so that the parent performs some modification on the value passed to it by the child component. In the parent component properties to be passed are listed so that the child component can use those properties as an attribute name and assign a value when referencing the child instance. Vue props allow a parent component to pass DATA to a child component. Props are used for passing data down the component tree; to pass data up the component tree (from child to parent), you can use $emit() or Vuex Create a component in Vue and pass a description object. The description.props field specifies what props the component can receive. The easiest way is to list your props as an array of property names. In the below example, the GREET component takes in a single prop, name. It then uses the name prop in its template. Vue.component('greet', { props: ['name'], template: ` <DIV> Hello, {{name}} </div> ` }); CONST app = new Vue({ template: `<greet name="Universe!"></greet>` });The name prop is passed to greet as a static prop in the above example in the Vue app. In other words, 'Universe' is a hard coded string. To pass dynamic prop (a prop bound to a variable), prefix the name with v-bind: when creating the component: Vue.component('greet', { props: ['name'], // Renders "Hello, Universe" template: ` <div> Hello, {{name}} </div> ` }); const app = new Vue({ data: () => ({ value: 'Universe' }), // Note the `v-bind:` prefix. If you forget it, `greet` will treat // 'value' as a raw string and render "Hello, value" template: `<greet v-bind:name="value"></greet>` });All props follow a one-way binding which is a down-way binding between the child's 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 other way (child to the parent which is carried out by emitting events rather than using props). |
|
| 36. |
What are the differences and similarities between v-if and v-show directives? |
Answer»
Their similarity is that both are involved in adding or removing DOM elements. What makes them different is v-if uses conditions while v-show uses CSS properties to determine WHETHER to add an element or not. |
|
| 37. |
Declarative-rendering is a common phenomenon in Vue.js and other frameworks. What is it and how is it achieved in Vue.js? |
|
Answer» In the past JavaScript used domineering methods to INFLUENCE DOM but over time, it has become outdated. Declarative rendering has taken precedence in recent times. Declarative rendering allows data to decide how the DOM is RENDERED. With Vue.js we are able to input and let the framework TAKE precedence and display the output correctly. When rendering data in Vue.js, we use curly braces as place holders to insert data into the DOM. With the above capability, Vue.js ability has been elevated to power deep sophisticated single page applications with the help of few modern TOOLS. It has a powerful enough library to EXECUTE and hold complex operations. Below is an example of a declarative instance: Const parent = new Vue ({ el : ‘#parent’, data : { name : ‘ Vue.js’ } })The above programme outputs a message “ Welcome to the exciting world of Vue.js |
|
| 38. |
Ensuring that the defined CSS styles in single files are applied singularly to a component is a vital skill for a Vue.js developer. How would you achieve this if applied to one component only? |
|
Answer» Modern applications USING CSS files tend to grow with TIME to levels that certain styles cannot be EASILY traced. This makes it DIFFICULT to even initiate a change or an update on the styles. Although single file components has allowed DEVELOPERS to grow in writing more logical ways compared to writing them in several languages, tracking certain styles in huge applications is quite difficult. Thanks to scoped styles, such challenges have been curbed. Scoped styles allow us to put down CSS that only apply to the components we need. An example of applied scoped styles is shown below. <style scoped> .example { Color: red; } </style> <template> <div class=”example”>hi</div> </template>In this example, the example class will only apply to that particular component only. This is accomplished by putting another data attribute to serve all the other elements within that particular component that are still engulfed by the initial CSS. Doing this does not prevent the styles from being influenced by other exterior styles, only that scoped styles are selfish. They do not allow leakage of their styles to other components. There are many other Vue styles such as deep styles, slotted styles, global styles, style modules among many other styles. They perform different but closely related functions to the scoped styles. |
|
| 39. |
More often developers tend to use the letters “vm”. They use it as a variable name to declare the root Vue application instance. What do the letters refer to for this case? |
|
Answer» Finding an easier way of performing tasks is one of the major functions of developers. Finding ways of DECLARING instances in a more simple way has led to the use of the two letters ‘vm’ to declare variable instances. Every vue instance begins by creating a completely fresh Vue instance. This uses the vue function. Var vm = new Vue ( { })Above is an illustration of how instance declaration is done in Vue. To some extent, we can say that Vue instance declaration was inspired by the Model-View-View-Model (MVVM) pattern. vm SHORT form for ViewModel has earned the status of conventional instance declaration in vue. Many vue applications have root Vue instances embedded with new Vue are organized into NESTED trees with reusable mechanisms. Naming an instance as vm is not compulsory, ALTHOUGH many developers use it this way. As long as a compiler is able to compile successfully with minimal ERRORS and produce an output on the template, any naming can be used so long as it is easy and simple to understand. |
|
| 40. |
Vue.js has several lifecycle hooks. What is your understanding of lifecycle hooks as used in vue.js? |
|
Answer» Vue instances undergo a lot of process from the moment they are initialized to the point where they are wrecked and exterminated. Lifecycle in vue is the compilation of activities right from data set up and observation to compiling the template, to mounting of the methods in the Direct Object Method (DOM), to bringing up-to-date the DOM as a result of data change. While those activities are taking place inside the DOM, some functions are naturally performed in them. Those functions are what are called lifecycle hooks. The diagrammatic representation below illustrates the various processes of the vue lifecycle. Vue has eight major lifecycle hooks. They are; created, before created, mounted, before mounted, updated, before updated, destroyed and before destroyed. All these lifecycle hooks play a VITAL ROLE in vue.js framework. Before creation is the first lifecycle that gets called immediately an instance is initialized. It is visualized as shown below: <template>, <div> < h1 >Vue Lifecycle hooks</h1> <ul> <li v-for="(item, n) in LIST" :key="n"> {{ item }} <a @click="deleteItem(item)">Delete</a> </li> </ul> <strong >Add a new item in the list array and save while running localhost to preview the destroy hooks</strong> </div> </template> <script> export default { data() { return { list: [ 'Apex Legends', 'A Plague Tale: Innocence', 'ART SQOOL', 'Baba Is You', 'Devil May Cry 5', 'The Division 2', 'Hypnospace Outlaw', 'Katana ZERO', ], } }, methods: { deleteItem(VALUE) { this.list = this.list.filter(item => item !== value) }, }, beforeCreate() { alert('beforeCreate: data is static, thats it') }, created() { alert('created: data and events ready, but no DOM') }, beforeMount() { alert('beforeMount: $el not ready') }, mounted() { alert('mounted: DOM ready to use') }, beforeUpdate() { alert( 'beforeUpdate: we know an update is about to happen, and have the data' ) }, updated() { alert('updated: virtual DOM will update after you click OK') }, beforeDestroy() { alert('beforeDestroy: about to blow up this component') }, destroyed() { alert('destroyed: this component has been destroyed') }, } </script> <style lang="scss" scoped> ul { padding-left: 0; } li { display: block; list-style: none; + li { margin-top: 10px; } } a { display: inline-block; BACKGROUND: rgb(235, 50, 50); padding: 5px 10px; border-radius: 10px; font-size: 10px; color: white; text-transform: uppercase; text-decoration: none; } </style> The lifecycle hooks are called in a sequence beginning with the “before” then followed by the original. An example of a running program is as below new Vue({ data: { b: 1 }, created: function () { // ‘this’ points to the vm instance console.log( ba is: ’ + this.b) } }) // => “b is: 1” |
|
| 41. |
Passing of data from a primary component to a secondary component is a common feature for Vue.js and Angular.js. How would you achieve data pass from parent to child component in Vue.js? |
|
Answer» Just like in the real world, parents are viewed as a source of knowledge or better less more experience. A child seeks more information from a parent and the parent either teaches or writes down steps and procedures to be followed. In the development world and as in our case, Vue.js FRAMEWORK, DATA is passed to a child component through attributes or as attributes. Data can be passed inline or using the component method. Methods are the reusable vue requests that separate the code and the modular. Its incorporation has helped to reduce REPETITIONS. Props are the most commonly used passage. They are one way inlets in the component. <Script> Export default { Name: ‘child’, Props: { parentData: Object, stringProp: String, title: String } } </script>In the above example, the prop is declared in the child section for it to appear as a normal variable. |
|
| 42. |
How would you describe computed properties in Vue.js? |
|
Answer» Vue.js provides an amazing platform for achieving dynamism or static values to be visual on the template. The use of DIRECT hardcoding into the HTML, text outburst or MODEST expressions to transform the data has been a way for achieving the basics. Complex computations have necessitated the development of computed properties. Computed property declaratively describes how one value solely depends on other values. Computed properties have revolutionized complex expressions in that we can create properties which can alter, manipulate, transform and present information in a more readable, efficient and UNDERSTANDABLE manner. Computed properties use methods in its library which is a huge plus. Methods are ALWAYS recomputed when ACCESSED unlike computed property which does not recompute thus providing accurate outputs. Computed properties can be used in so many ways. Data filtering, calculations, execution of Boolean conditions are just a few of the applications of computed properties. Below is a basic example of a computed property that uses count: <div> </template> <script> Export default { name: “HelloWorld”, data() { return{ ShopNumber: 2 } }, Computed: { Count: function() { Return ‘The shop number is ‘ + this.shopNumber } } }; </script> <div>From the above count property, this.shopNumber is the dependency data and it returns a sentence that has this.shopnumber that is displayed in the template. |
|
| 43. |
What is the directive in Vue.js? |
|
Answer» Directive is a PIECE of instruction to perform a certain task. In vue.js a directive is a sign that that directs the LIBRARY to perform an action to the DOM. Directives in Vue.js are much simpler to understand compared to in Angular.js. Directives in vue.js are in HTML prefix format. Some of the directives INCLUDE; V-show, v-if, v-on, v-for, v-bind and v-model. They appear in the following format; <element Prefix-directiveId=”[argument:] expression [| filters…]”> </element>Directives give permission to the template to act according to the changes in accordance to the defined logic by use of methods, data PROPERTIES and inline expressions. An example of a directive is below. <SignUpButton V-On:click= “doSignup” />Here, a v-on directive is used to implement a click on the component. The message is to perform or allow the user to sign up. Apart from the above-mentioned directives, vue.js allows us to define our own directives based on what we need to perform. V directives are easier to understand and implement in the development world. Developers are prioritizing it although prior knowledge in Angular or any other structure is an added advantage. Prior knowledge provides a baseline for understanding how Document Object Model works and how directives manipulate it. |
|
| 44. |
While juggling through the world of development using vue.js, you are required to use a two-way data binding between the data attribute and an input box. How would you implement this? |
|
Answer» Two-way data binding refers to data sharing between components class and the template. Two way binding is a powerful tool for developing JavaScript patterns. For instance when one side is changed, the other also CHANGES to match the other. When a value is altered or changed in the input box, the value of the component class also changes. The best way to implement two-way data binding is by the use of v-model. V-model is essential as it allows updating of data. V-model assumes VUE instance as the primary source of data and thus it ignores initial checked, selected or value attributes. The initial VALUES only need to be declared in the JavaScript. For instance: <input type=”text” :value=”nameInput” @keyup= “nameInput = $EVENT.target.value”>The data attribute ‘nameInput’ is assigned the input box when there is an event in ‘keyup’. This way, we are binding the input box to the data attribute and that is how two-way binding is achieved. There is a firm RELATIONSHIP flanked by the form field and information property. Compared to manual setup, v-model handles the process quicker and more efficiently. |
|
| 45. |
As a developer, you notice that developing a Single Page Application (SPA) requires routing. How would you achieve/use routing? |
|
Answer» One of the unique features of vue.js is routing in Single Page Applications. The vue router allows the transition from one page to another page on the user interface without NECESSARILY the need for request from the server. Routing in Single Page Applications is achieved through the use of vue-router library. The collection offers a variety of feature sets such as the personalized/customized scroll behavior, transitions, nested routes, HTML5 history MODE and route structures and wildcards. Vue router also allows integration of some third party routers. In vue applications, vue router is the library that allows navigation on the APP. An example of achieved routing is in vue app. In the application, it is easier to move from one page to another thanks to the vue router. Most of the modern single page applications use the vue router. To build a simple page component without using the full features of router library, simple routing is required as in the example below: const NotFound = { template: '<p>Page not found</p>' } const Home = { template: '<p>home page</p>' } const About = { template: '<p>about page</p>' } const routes = { '/': Home, '/about': About } new Vue({ el: '#app', data: { currentRoute: window.location.pathname }, COMPUTED: { ViewComponent () { return routes[this.currentRoute] || NotFound } }, render (h) { return h(this.ViewComponent) } }) |
|
| 46. |
Vue.js is commonly referred to as a ‘progressive framework’. What is your typical understanding of progressive framework in vue.js? |
|
Answer» Vue.js is not only a progressive framework, it is known by developers as the progressive framework. Vue.js has earned its progressive framework term due to its unique characteristics. Although it is simple and flexible, it has various powerful features which attract many developers. It is still fresh in the development world, easy to maneuver and fairly direct. Vue.js permits the development of any desired application structure which frameworks such as Angular.js and React.js do not OFFER. Also, vue.js is an open-source framework. This particularly means a lot in the development environment. It is highly versatile and lightweight in nature. It is the view which allows the DISPLAY of data packets in single-page applications. Those few mentioned QUALITIES among many others have earned vue.js its ‘progressive nature’ badge. Vue.js is a user-friendly framework. It is the best choice for beginners due to its ease of use. For the experienced developers, vue.js library provides a view layer. One can PICK it and integrate with any other framework. As an HTML developer, the use of vue.js makes you realize how its learning curve is quite forgiving. It is FAIR to say vue.js was created as a simple version of all the other complex frameworks. |
|