Home / Past papers / MAD2 Quiz 2 / this paper

In Vue.js reactivity system, when is a computed property re-evaluated?

What is the correct way to implement two-way data binding in a custom component in Vue.js 2?

What distinguishes a Progressive Web App (PWA) from a traditional web application?

Consider the below javascript program.
```javascript
function testScope() {
if (true) {
var x = 10;
let y = 20;
}
console.log(x);
console.log(y);
}
testScope();
```
What will be the output of the above program?
10 undefined

undefined 10

10 Error

Error

Consider the below javascript program.
```javascript
let count = 0;
async function increment() {
const incrementCount = () => {
return new Promise(resolve => {
setTimeout(() => {
count++;
resolve(count);
}, 100);
});
};
const results = await Promise.all([incrementCount(), incrementCount(), incrementCount()]);
console.log(results);
}
increment();
console.log("Start");
```
What will be the output of the above program?
[1, 1, 1] Start

Start [1, 1, 1]

[1, 2, 3] Start

Start [1, 2, 3]

Consider the below javascript program.
```javascript
const obj = { a: 1, b: 2 };
const { a, ...rest } = obj;
console.log(a, rest);
```
What will be the output of the above program?
Consider the below Vue router setup.
```javascript
const Product = {
template: `<div><h1>Product {{ $route.params.id }}</h1></div>`
};
const ProductReviews = {
template: `<div><h2>Reviews for Product</h2></div>`
};
const routes = [
{
path: '/products/:id',
component: Product,
children: [
{
path: 'reviews',
component: ProductReviews
}
]
}
];
const router = new VueRouter({
routes
});
```
What will be the behavior when the user visits "/products/123/reviews"?
Consider the below Vuex setup.
```javascript
const store = new Vuex.Store({
state: {
cart: [
{ id: 1, name: 'Item 1', price: 100 },
{ id: 2, name: 'Item 2', price: 200 }
]
},
getters: {
totalPrice(state) {
return state.cart.reduce((total, item) => total + item.price, 0);
}
},
mutations: {
addToCart(state, item) {
state.cart.push(item);
}
},
actions: {
addItemToCart({ commit }, item) {
commit('addToCart', item);
}
}
});
```
What will happen if the user dispatches the "addItemToCart" action to add a new item to the cart?
Consider the following javascript code.
```javascript
async function fetchData() {
try {
const response = await fetch('https://api.example.com/data');
if (!response.ok) throw new Error('HTTP error');
const data = await response.json();
return data;
} catch (error) {
if (error.name === 'TypeError') {
return { status: 'network error' };
}
return { status: 'http error' };
}
}
```
When the function is called what will be returned if the server is **unreachable**?
Consider the following javascript code.
```javascript
function translateToEmoji(msg, dictionary, cb) {
const translated = msg
.split(' ')
.map(word => dictionary[word] || word);
cb(translated.join(' '));
}
translateToEmoji('i love code',
{ heart: '❤️', code: '💻' },
result => console.log(result));
```
What's logged?
"i love code"

"I ❤️ 💻"

"undefined undefined undefined"

"i love 💻"

Consider the following html with relevant vue cdn links added.
```html
<div id="app">
<button @click="addLike">Like</button>
<div>{{likes}}</div>
</div>
<script>
new Vue({
el: '#app',
data: () => ({
likes: 0,
lastClick: 0
}),
methods: {
addLike() {
if (Date.now() - this.lastClick < 500) {
this.likes += 2;
} else {
this.likes += 1;
}
this.lastClick = Date.now();
}
}
})
</script>
```
Consider the following html with relevant vue cdn links added.
```html
<div id="app">
<async-component ref="child"></async-component>
<button @click="updateParent">Update Parent</button>
</div>
<script>
Vue.component('async-component', {
template: '<div>{{message}}</div>',
data() {
return {
message: 'Initial'
}
},
mounted() {
setTimeout(() => {
this.message = 'Updated in child'
}, 0)
}
})
new Vue({
el: '#app',
mounted() {
this.$refs.child.message = 'Updated in parent'
},
methods: {
updateParent() {
this.$refs.child.message = 'Button clicked'
}
}
})
</script>
```
Consider the below javascript program.
```javascript
const promiseChain = new Promise((resolve, reject) => {
console.log('Step 1');
resolve(1);
})
.then((value) => {
console.log('Step 2:', value);
return value + 1;
})
.then((value) => {
console.log('Step 3:', value);
throw new Error('Error in Step 3');
})
.then((value) => {
console.log('Step 4:', value);
return value * 2;
})
.catch((err) => {
console.log('Caught:', err.message);
return 5;
})
.then((value) => {
console.log('Step 5:', value);
return value + 1;
});
console.log('End of Code');
```
What will be the output of the above program?
Consider the below Vue router setup.
Note: Assume that the API "/api/users/userId" is operational and returns the user's data including name.
```javascript
const UserProfile = {
template: `<div><h2>User Profile</h2><p>{{ user.name }}</p></div>`,
data() {
return {
user: {}
};
},
created() {
this.fetchUserData();
},
methods: {
async fetchUserData() {
const userId = this.$route.query.userId;
const response = await fetch(`/api/users/${userId}`);
this.user = await response.json();
}
}
};
const routes = [
{ path: '/user', component: UserProfile }
];
const router = new VueRouter({
routes
});
```
What will happen if the user navigates to "/user?userId=123"?
Consider the below Vue.js application.
```html
<template>
<div>
<button @click="goToPage('Home')">Go to Home</button>
<button @click="goToPage('About')">Go to About</button>
<button @click="goToPage('Contact')">Go to Contact</button>
<div v-if="visitedPages.length">
<h3>Visited Pages:</h3>
<ul>
<li v-for="(page, index) in visitedPages" :key="index">{{ page }}</li>
</ul>
</div>
</div>
</template>
<script>
export default {
data() {
return {
visitedPages: []
};
},
mounted() {
const storedPages = JSON.parse(sessionStorage.getItem('visitedPages')) || [];
this.visitedPages = storedPages;
},
methods: {
goToPage(page) {
this.visitedPages.push(page);
sessionStorage.setItem('visitedPages',
JSON.stringify(this.visitedPages));
this.$router.push(`/${page.toLowerCase()}`);
}
}
};
</script>
```
Consider the below Vue.js application.
```html
<template>
<div>
<input v-model="name" placeholder="Enter name">
<input v-model="email" placeholder="Enter email">
<button @click="submitForm">Submit</button>
</div>
</template>
<script>
export default {
data() {
return {
name: '',
email: ''
};
},
mounted() {
if (localStorage.getItem('formData')) {
const savedData = JSON.parse(localStorage.getItem('formData'));
this.name = savedData.name;
this.email = savedData.email;
}
},
watch: {
name(newVal) {
localStorage.setItem('formData', JSON.stringify({ name: newVal, email: localStorage.email }));
},
email(newVal) {
localStorage.setItem('formData', JSON.stringify({ name: localStorage.name, email: newVal }));
}
},
methods: {
submitForm() {
localStorage.removeItem('formData');
this.name = '';
this.email = '';
}
}
};
</script>
```
What will happen if the user submits the form and reloads the page?Auto-generated summary from the source site. Handy as a checklist; the lessons above explain each idea from scratch.
Vue.js Reactivity System
v-model with corresponding props and emits.Progressive Web Apps (PWAs)
JavaScript Scope and Asynchronous Operations
var, let, and const.Vue Router
Vuex
Error Handling in JavaScript
JavaScript Functions and Callbacks
Vue.js Lifecycle Hooks
mounted hook is called.Session and Local Storage
javascript function testScope() { if (true) { var x = 10; let y = 20; } console.log(x); // Output: 10 console.log(y); // Output: Error (y is not defined) } testScope(); ``javascript async function increment() { const incrementCount = () => { return new Promise(resolve => { setTimeout(() => { count++; resolve(count); }, 100); }); }; const results = await Promise.all([incrementCount(), incrementCount(), incrementCount()]); console.log(results); // Output: [1, 2, 3] } ``javascript const obj = { a: 1, b: 2 }; const { a, ...rest } = obj; console.log(a, rest); // Output: 1 { b: 2 } ``javascript const routes = [ { path: '/products/:id', component: Product, children: [ { path: 'reviews', component: ProductReviews } ] } ]; ``javascript const store = new Vuex.Store({ state: { cart: [ { id: 1, name: 'Item 1', price: 100 }, { id: 2, name: 'Item 2', price: 200 } ] }, getters: { totalPrice(state) { return state.cart.reduce((total, item) => total + item.price, 0); } }, mutations: { addToCart(state, item) { state.cart.push(item); } }, actions: { addItemToCart({ commit }, item) { commit('addToCart', item); } } }); ``javascript async function fetchData() { try { const response = await fetch('https://api.example.com/data'); if (!response.ok) throw new Error('HTTP error'); const data = await response.json(); return data; } catch (error) { if (error.name === 'TypeError') { return { status: 'network error' }; } return { status: 'http error' }; } } ``javascript export default { data() { return { visitedPages: [] }; }, mounted() { const storedPages = JSON.parse(sessionStorage.getItem('visitedPages')) || []; this.visitedPages = storedPages; }, methods: { goToPage(page) { this.visitedPages.push(page); sessionStorage.setItem('visitedPages', JSON.stringify(this.visitedPages)); this.$router.push(/${page.toLowerCase()}); } } }; ``javascript export default { data() { return { name: '', email: '' }; }, mounted() { if (localStorage.getItem('formData')) { const savedData = JSON.parse(localStorage.getItem('formData')); this.name = savedData.name; this.email = savedData.email; } }, watch: { name(newVal) { localStorage.setItem('formData', JSON.stringify({ name: newVal, email: localStorage.email })); }, email(newVal) { localStorage.setItem('formData', JSON.stringify({ name: localStorage.name, email: newVal })); } }, methods: { submitForm() { localStorage.removeItem('formData'); this.name = ''; this.email = ''; } } }; ``