Home / MAD2 / Week 7 / Real questions
60 questions pulled from past papers whose wording matches this week's topics, newest first, duplicates removed. Pick your answers, then press Check answers. Figures and answer keys are the originals.
The
getter is used in a Vue component as shown below:
Now suppose the Vuex getter
is removed, while the temperature state continues to be updated through Vuex mutations. Which of the following implementations correctly recreates
in the component so that it automatically reacts whenever the Vuex
changes?```javascript
const store = new Vuex.Store({
state: {
temperature: 30
},
getters: {
weatherStatus(state) {
return state.temperature >= 35 ? "Hot" : "Normal"
}
}
})
```
weatherStatus
```javascript
computed: {
weatherStatus() {
return this.$store.getters.weatherStatus
}
}
```
weatherStatus
weatherStatus
temperature
```javascript
computed: {
weatherStatus() {
return this.$store.state.temperature >= 35
? "Hot"
: "Normal"
}
}
```
```javascript
watch: {
weatherStatus() {
return this.$store.state.temperature >= 35
? "Hot"
: "Normal"
}
}
```
```javascript
methods: {
weatherStatus() {
this.$store.state.temperature >= 35
? "Hot"
: "Normal"
}
}
```
```javascript
watch: {
weatherStatus() {
return this.$store.state.temperature >= 35
}
}
```
Based on the above data, answer the given subquestions.
pauses the execution of the
function until the Promise resolves.await ``` display() ```
immediately returns the resolved string "Data Received".``` fetchData() ```
functions cannot return a
.async Promise
would cause
to store a
object instead of the resolved value.await result Promise
Note: All three image above are of one html. Based on the above data, answer the given subquestions.

component

, what values are logged by the two
statements, immediately after commit and dispatch are called (before the 1-second timeout completes)?``` handleClick() ``` ``` console.log ```
component

is defined as a
while
is defined as an
?``` increment ``` mutation ``` incrementAsync ``` action

```
mutations: {
ADD_TO_CART(state, product) {
state.cart.push(product)
}
}
```
```javascript
mutations: {
ADD_TO_CART(state, product) {
setTimeout(() => {
state.cart.push(product)
}, 500)
}
}
```
```javascript
mutations: {
ADD_TO_CART(state, product) {
fetch('/api/add').then(() => {
state.cart.push(product)
})
}
}
```
```javascript
mutations: {
ADD_TO_CART(state, product) {
Promise.resolve().then(() => {
state.cart.push(product)
})
}
}
```
```javascript
const store = new Vuex.Store({
state: {
discount: 10,
products: [
{name: 'apple',
price: 120
},
{
name: 'banana',
price: 60
}
]
},
mutations: {
reducePrice: state=>{
// Code1
}
}
})
```
```javascript
this.$store.state.products.forEach(product => { product.price -= (state.discount)/100*product.price; })
```
```javascript
state.products.forEach(product => { product.price -= (state.discount)/100*product.price;})
```
```javascript
commit.products.forEach(product => { product.price -= (state.discount)/100*product.price;})
```
```javascript
dispatch.products.forEach(product => { product.price -= (state.discount)/100*product.price;})
```
Component.vue
After triggering all three methods (
,
and
) one by one, which of the following statements is correct?```javascript
const store = new Vuex.Store({
state: {
cart: []
},
mutations: {
ADD_TO_CART(state, product) {
state.cart.push(product)
}
},
actions: {
addToCart({ commit }, product) {
setTimeout(() => {
commit('ADD_TO_CART', product)
}, 500)
}
}
})
```
```javascript
methods: {
addItem_A(product) {
this.$store.commit('ADD_TO_CART', product)
},
addItem_B(product) {
this.$store.dispatch('addToCart', product)
},
addItem_C(product) {
this.$store.state.cart.push(product)
}
}
```
addItem_A
addItem_B
addItem_C
and
will appear in Vue DevTools mutation history, but
will appear with a delay.addItem_A addItem_B addItem_B
will update the cart because mutations cannot be called directly from components.addItem_B
will throw an error because Vuex prevents direct state modification.addItem_C
If the addItemAsync action is dispatched with the item 'React', what will be the state of items after 2 seconds?```javascript
const store = new Vuex.Store({
state: {
items: ['Angular', 'Vue'],
},
mutations: {
addItem(state, item) {
state.items.push(item);
},
},
actions: {
addItemAsync({ commit }, item) {
setTimeout(() => {
commit('addItem', item);
}, 500);
},
},
});
```
Which of the following options correctly fills Line X and Line Y so that the application works as expected?```html
<div id="app">
<h3>Trip Essentials</h3>
<ul>
<li v-for="item in packedItems" :key="item">
{{ item }}
</li>
</ul>
<button @click="packItem('Passport')">Pack Passport</button>
</div>
<script>
const store = new Vuex.Store({
state: {
packed: []
},
mutations: {
ADD_ITEM(state, item) {
state.packed.push(item);
}
}
});
new Vue({
el: "#app",
store,
computed: {
/* Line X */
},
methods: {
packItem(item) {
/* Line Y */
}
}
});
</script>
```
```javascript
// Line X
packedItems() {
return this.store.state.packed;
}
// Line Y
this.store.commit("ADD_ITEM", item);
```
```javascript
// Line X
packedItems() {
return this.$store.state.packed;
}
// Line Y
this.$store.commit("ADD_ITEM", item);
```
```javascript
// Line X
packedItems() {
return this.$store.packed;
}
// Line Y
this.commit("ADD_ITEM", item);
```
```javascript
// Line X
packedItems: this.$store.state.packed
// Line Y
this.$store.dispatch("ADD_ITEM", item);
```
``` git checkout -b feature-branch ```

``` git add . ```

``` git commit -m "Initial commit" ```

``` git push origin feature-branch ```

``` git branch feature-branch && git checkout main ```

``` git push feature-branch origin ```
What will be printed on the console first?```javascript
const store = new Vuex.Store({
state: { todos: [] },
mutations: {
addTodo(state, todo) { state.todos.push(todo) }
},
actions: {
async addTodoAsync({ commit }, todo) {
commit('addTodo', { text: todo, done: false });
return 'done';
}
}
});
store.dispatch('addTodoAsync', 'Learn Vuex')
.then(msg => console.log(msg));
console.log(store.state.todos.length);
```
Suppose the following mutation is committed:store.commit("updateUserStatus", { userId: 2, status: "active" });. Which of the following statements is TRUE after this mutation is executed?```javascript
const store = new Vuex.Store({
state: {
users: [
{ id: 1, name: 'Alice', status: 'active', role: 'admin' },
{ id: 2, name: 'Bob', status: 'inactive', role: 'user' },
{ id: 3, name: 'Charlie', status: 'active', role: 'user' }
]
},
getters: {
activeUsers(state) {
return state.users.filter(user => user.status === 'active');
},
activeUserCount(state, getters) {
return getters.activeUsers.length;
},
adminUsers(state) {
return state.users.filter(user => user.role === 'admin');
}
},
mutations: {
updateUserStatus(state, { userId, status }) {
const user = state.users.find(u => u.id === userId);
if (user) {
user.status = status;
}
}
}
});
```
will return 3``` activeUserCount ```
will return two usersadminUsers
will include only Alice and CharlieactiveUsers
And JavaScript code:
What are the values of id and action respectively?```html
<button id="btn1" data-action="delete" data-id="42">Delete</button>
```
```javascript
const btn = document.getElementById('btn1');
const id = btn.dataset.id;
const action = btn.getAttribute('data-action');
```
Which of the following is the correct matching?| Storage Type | Characteristic | | :---------------- | :-------------------------------------------------------------------------------- | | 1. Session Storage | A. Data automatically encrypts itself without developer intervention. | | 2. Token Storage | B. Data persists only until the browser/tab is closed. | | 3. Cookie Storage | C. Often used to store authentication tokens securely on the client side. | | | D. Data persists across sessions, typically stored on the client and sent with every HTTP request. |

``` git checkout main git merge appdev2 git commit -m "Merged main into appdev2" ```

``` git merge main git commit -m "Merged main into appdev2" ```

``` git checkout appdev2 git pull origin main git commit -m "Pulled changes from main into appdev2" ```

``` git merge appdev2 main git commit -m "Merged main into appdev2" ```

```javascript
const saveToken = (token) => {
sessionStorage.setItem('authToken', token);
};
const getToken = () => {
return sessionStorage.getItem('authToken') || null;
};
```
The `localStorage` object stores data with no expiration date, even after the browser is closed.

The `sessionStorage` object keeps data only for the duration of the page session.

Both `localStorage` and `sessionStorage` can store data in key-value pair format.

Data stored in `sessionStorage` is available across different browser tabs.

Consider the following Vue 2 code with Vuex 3 used via CDN, assume the Vuex
store is correctly injected into the Vue instance.
Filename: store.js
```javascript
export default store = new Vuex.Store({
state: {
score: 10,
},
mutations: {
increaseScore(state) {
state.score += 5;
},
},
actions: {
increaseScoreAsync({ commit }) {
setTimeout(() => {
commit("increaseScore");
}, 1000);
},
},
});
```
Filename: score-display.js
```javascript
export default Vue.component('score-display', {
template: `
<div>
<p>Current Score: {{ score }}</p>
<button @click="boostNow">Boost Now</button>
<button @click="boostLater">Boost After 1s</button>
</div>
`,
computed: {
score() {
// CODE 1
}
},
methods: {
boostNow() {
// CODE 2
},
boostLater() {
// CODE 3
}
}
});
```
Which of the following correctly fills in CODE 1, CODE 2, and CODE 3 for the score to be
displayed and for the **boostNow()** and **boostLater()** methods to work correctly?
CODE 1: ``` return this.$store.state.score; ```

CODE 2:
```
this.$store.commit('increaseScore');
```
``` CODE 2: this.increaseScore() ; ```

CODE 3:
```
this.$store.dispatch('increaseScoreAsync');
```
CODE 3: ``` this.$store.increaseScoreAsync(); ```

Consider the following Vue application with markup "index.html" and JavaScript file "app.js".
Filename: index.html
```html
<div id="app">
<data-panel>
<template #sidebar>
<span>Navigation Menu</span>
</template>
<template #actions>
<button>Save Changes</button>
<button>Cancel</button>
</template>
<template #default>
<h3>Main Dashboard</h3>
<p>Welcome to the control panel</p>
</template>
<template #footer>
<small>Last updated: Today</small>
</template>
<div>Extra content outside templates</div>
</data-panel>
</div>
```
Filename: app.js
```javascript
Vue.component("data-panel", {
template: `<div class="panel">
<header>
<slot name="sidebar"></slot>
</header>
<main>
<slot></slot>
</main>
<section>
<slot name="actions"></slot>
</section>
<footer>
<slot name="summary"></slot>
</footer>
</div>`,
});
const app = new Vue({
el: "#app",
});
```
What will be the visual output displayed in the browser?
Navigation Menu Main Dashboard Welcome to the control panel Extra content outside templates Save Changes Cancel Last updated: Today

Navigation Menu Main Dashboard Welcome to the control panel Extra content outside templates Save Changes Cancel

Navigation Menu Extra content outside templates Save Changes Cancel

Navigation Menu Main Dashboard Welcome to the control panel Save Changes Cancel Last updated: Today

Consider the following Vuex store setup for a user management system:
```javascript
const store = new Vuex.Store({
state: {
users: [
{ id: 1, name: 'Alice', status: 'active', role: 'admin' },
{ id: 2, name: 'Bob', status: 'inactive', role: 'user' },
{ id: 3, name: 'Charlie', status: 'active', role: 'user' }
]
},
getters: {
activeUsers(state) {
return state.users.filter(user => user.status === 'active');
},
activeUserCount(state, getters) {
return getters.activeUsers.length;
},
adminUsers(state) {
return state.users.filter(user => user.role === 'admin');
}
},
mutations: {
updateUserStatus(state, { userId, status }) {
const user = state.users.find(u => u.id === userId);
if (user) {
user.status = status;
}
}
}
});
```
```javascript
addUser(state, user) {
state.users.push({ ...user, id: Date.now() });
},
actions: {
toggleUserStatus({ commit, state }, userId) {
const user = state.users.find(u => u.id === userId);
if (user) {
const newStatus = user.status === 'active' ? 'inactive' : 'active';
commit('updateUserStatus', { userId, status: newStatus });
}
},
async createUser({ commit }, userData) {
await new Promise(resolve => setTimeout(resolve, 100));
commit('addUser', userData);
}
}
```
What will happen when the following sequence of operations is executed?
```javascript
store.dispatch('toggleUserStatus', 1); // Toggle Alice's status
store.dispatch('createUser', { name: 'David', status: 'active', role: 'user' });
```
The activeUserCount will become 1 immediately after the first dispatch, and remain 1 after the second dispatch completes.

The activeUserCount will become 1 after the first dispatch, and become 2 after the second dispatch completes.

The activeUserCount will remain 2 after the first dispatch, and become 3 after the second dispatch completes.

The activeUserCount will become 3 immediately after both dispatches, since both operations run synchronously.

Consider the below Vuex store configuration:
```javascript
const store = new Vuex.Store({
state: {
items: [],
},
mutations: {
addItem(state, item) {
state.items.push(item);
},
},
actions: {
addItemAsync({ commit }, item) {
setTimeout(() => {
commit('addItem', item);
}, 1000);
},
},
});
```
If the addItemAsync action is dispatched with the item 'Vue.js', what will be the state of items after 2 seconds?
The image shows a single vertical bar character.

``` ['Vue.js', 'Vue.js'] ```

``` ['Vue.js'] ```

[object]
Consider the below Vuex setup.
What is logged to the console immediately after dispatching the action?```javascript
const store = new Vuex.Store({
state: {
value: 0
},
mutations: {
setValue(state, payload) {
state.value = payload;
}
},
actions: {
async updateValue({
commit
}) {
const newValue = await fetchData();
commit('setValue', newValue);
}
}
});
function fetchData() {
return new Promise(resolve => {
setTimeout(() => resolve(42), 2000);
});
}
store.dispatch('updateValue');
console.log(store.state.value);
```
Consider the below Vuex store configuration.
```javascript
const store = new Vuex.Store({
state: {
count: 0,
},
mutations: {
increment(state) {
state.count++;
},
},
});
```
And the below Vue component:
```html
<template>
<div>
<button @click="increment">Increment</button>
<p>Count: {{ count }}</p>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
export default {
computed: {
...mapState(['count']),
},
methods: {
...mapMutations(['increment']),
},
};
</script>
```
What will be displayed in the placeholder "{{ count }}" on the browser after clicking the "Increment" button 3 times?
Consider the below Vuex store configuration:
```javascript
const store = new Vuex.Store({
state: {
items: ['Vue', 'React'],
},
mutations: {
removeItem(state, item) {
state.items = state.items.filter(i => i !== item);
},
},
actions: {
removeItemAsync({ commit }, item) {
setTimeout(() => {
commit('removeItem', item);
}, 500);
},
},
});
```
If the addItemAsync action is dispatched with the item 'Vue', what will be the state of items after 2 seconds?
Consider the below Vuex setup.
```javascript
const store = new Vuex.Store({
state: {
number: 10
},
mutations: {
updateNumber(state, payload) {
state.number = payload;
}
},
actions: {
async fetchNumber({ commit }) {
const fetchedValue = await getData();
commit('updateNumber', fetchedValue);
}
}
});
function getData() {
return new Promise(resolve => {
setTimeout(() => resolve(100), 1500);
});
}
store.dispatch('fetchNumber');
console.log(store.state.number);
```
What is logged to the console immediately after dispatching the action?
Consider the below Vuex store configuration.
```javascript
const store = new Vuex.Store({
state: {
count: 5,
},
mutations: {
decrement(state) {
state.count--;
},
},
});
```
And the below Vue component:
```html
<template>
<div>
<button @click="decrement">Decrement</button>
<p>Count: {{ count }}</p>
</div>
</template>
<script>
import { mapState, mapMutations } from 'vuex';
export default {
computed: {
...mapState(['count']),
},
methods: {
...mapMutations(['decrement']),
},
};
</script>
```
What will be displayed in the placeholder "{{ count }}" on the browser after clicking the "Decrement" button 4 times?
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 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?
What's the issue with this Vuex mutation? Assuming this mutation is part of vuex store.
```javascript
mutations: {
updateUser(state, userData) {
state.user = userData
state.lastUpdated = Date.now()
if (userData.role === 'admin') {
fetchAdminData().then(data => {
state.adminData = data
})
}
}
}
```
Given the following Vuex store setup.
```javascript
const store = new Vuex.Store({
state: {
counter: 0
},
mutations: {
increment(state) {
state.counter++;
}
},
actions: {
async incrementAsync({
commit
}) {
await new Promise(resolve => setTimeout(resolve, 1000));
commit('increment');
}
}
});
```
Assuming the store is correctly binded with a Vue app, what will be the correct behavior when the following code is executed?
`this.$store.dispatch('incrementAsync');`
Consider the following HTML, which includes Vue 2 and Vuex CDN links.
```html
<div id="app">
<p v-if="userData">User: {{ userData.name }}</p>
<p v-else>No user data available</p>
</div>
<script>
const store = new Vuex.Store({
state: {
userData: null
},
mutations: {
setUserData(state, data) {
state.userData = data;
}
},
actions: {
fetchUserData({ commit }) {
return fetch('https://httpstat.us/500')
.then(response => {
if (!response.ok) throw new Error('Network error');
return response.json();
})
.then(data => {
commit('setUserData', data);
},
error => {
commit('setUserData', { name: 'Luke' })
})
.catch(() => {
commit('setUserData', null);
});
}
}
});
new Vue({
el: '#app',
store,
created() {
this.$store.dispatch('fetchUserData');
},
computed: {
userData() {
return this.$store.state.userData;
}
}
});
</script>
```
What will be rendered on the browser, if the fetch request gets back 500 status code?
Suppose you are developing an application for millions of users that will perform intensive data analysis and return the results asynchronously. Arrange the following set of actions/operations to achieve an efficient and scalable design. I. Save the result to a database II. Invoke a callback URL III. Queue the analysis job

Consider the below Vuex implementation.
```javascript
const store = new Vuex.Store({
state: {
token: sessionStorage.getItem('authToken') || null
},
mutations: {
setToken(state, token) {
state.token = token;
sessionStorage.setItem('authToken', token);
},
clearToken(state) {
state.token = null;
sessionStorage.removeItem('authToken');
}
},
actions: {
login({ commit }, token) {
commit('setToken', token);
},
logout({ commit }) {
commit('clearToken');
}
}
});
```
After the user logs in with a token and refreshes the page, what will happen to the Vuex state and the session storage?
In a Vue CLI project with Vuex, you have the following configuration:
In a Vue CLI project with Vuex, you have the following configuration: src/store/index.js:
```javascript
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
export default new Vuex.Store({
state: {
value: "",
},
mutations: {
setValue(state, payload) {
state.value = payload;
}
},
actions: {
async fetchValue({ commit }) {
// Simulate async API call
const response = await new Promise(resolve => setTimeout(() =>
resolve('API Value'), 500));
commit('setValue', response);
}
}
});
```
src/App.vue:
```html
<template>
<div>
<p>{{ value }}</p>
<button @click="updateValue">Update Value</button>
</div>
</template>
<script>
export default {
computed: {
value() {
return this.$store.state.value;
},
},
methods: {
async updateValue() {
await this.$store.dispatch('fetchValue');
},
},
};
</script>
```
After running "npm run serve", if you click the "Update Value" button, what will be displayed in the `<p>` tag?
API Value

"" ""

undefined

null

Suppose you are organizing a felicitation program for the students with exemplary performance in the BS program. You have the scorecard of all the students. The administration has decided to shortlist the students based on the following 2 criteria:
1. The student must have an "S" in their MAD II project
2. The overall CGPA of the student must be greater than 8
Fill in the `code1` & `code2`, which can be used in Vuex Store to update the "awardees" state variable with the objects of those students who satisfy the above-mentioned criteria. The objects to be inserted in the "awardees" state variable must only have the student ID and a random token generated in the "send_task" action function.
```javascript
const store = new Vuex.Store({
state: {
bs_program: [{
student_id: 'stu1001',
mad2_grade: 'S',
cgpa: 8.35
}, {
student_id: 'stu1002',
mad2_grade: 'A',
cgpa: 8.78
}, {
student_id: 'stu1003',
mad2_grade: 'S',
cgpa: 9.1
}, {
student_id: 'stu1004',
mad2_grade: 'S',
cgpa: 7.44
}, ],
awardees: []
},
mutations: {
update_final(state, payload) {
for (student of state.bs_program)
code2
}
},
actions: {
send_task: function(context) {
const token = get_token(); // generates a random token
code1
}
}
})
```
```javascript
code1: this.$store.commit("update_final", {"min" : 8, "token" : token});
code2: if (student.mad2_grade != "S" && student.cgpa > 8) {
const obj = {};
obj.student_id = student.student_id;
obj.token = payload.token
state.awardees.push(student)
}
```
```
code1: context.commit("update_final", 8, token);
code2: if (mad2_grade != "S" && cgpa > 8){
awardees.push(company)
}
```
```javascript
code1: this.$store.commit("update_final", 8, token);
code2: if (mad2_grade != "S" && cgpa > 8){
awardees.push(company)
}
```
```
code1: context.commit("update_final", {"min" : 8, "token" : token});
code2: if (student.mad2_grade != "S" && student.cgpa > 8) {
const obj = {};
obj.student_id = student.student_id;
obj.token = payload.token
state.awardees.push(student)
}
```
Consider the following Vuex module definition for managing a shopping cart.
```javascript
const cartModule = {
state: {
items: []
},
mutations: {
addItem(state, item) {
state.items.push(item);
},
},
actions: {
async addToCart({ commit }, item) {
// TODO: Implement adding item to cart
},
},
}
```
Which of the following options correctly completes the code for the "addToCart" action function?
```javascript
addToCart({ commit }, item) {
commit('addItem', item);
}
```
```javascript
addToCart({ state, commit }, item) {
const existingItem = state.items.find(i => i.id === item.id);
if (existingItem) {
commit('addItem', existingItem);
} else {
commit('addItem', item);
}
}
```
```javascript
addToCart({ commit }, item) {
commit('addItem', { ...item });
}
```
All of these

Fill in property_name & definition, which can be used in Vuex Store to update the "best_food" state variable with the objects of those food items which have their calorific value less than 300.
```javascript
const store = new Vuex.Store({
state: {
foods: [
{ "name": "Sandwich", "calories": 100 },
{ "name": "Pizza", "calories": 1250 },
{ "name": "Chips", "calories": 700 }
],
best_food: []
},
=property_name=: {
get_best_food: function(state) {
======== definition ========
}
}
})
```
property_name : actions,
definition:
```
state.foods.forEach(food => {
if (food.calories < 300){
context.best_food.push(food)
}
});
```
property_name : actions,
definition:
```javascript
state.foods.forEach(food => {
if (food.calories < 300){
state.best_food.push(food)
}
});
```
property_name : mutations,
definition:
```javascript
state.foods.forEach(food => {
if (food.calories < 300){
context.best_food.push(element)
}
});
```
property_name : mutations,
definition:
```javascript
state.foods.forEach(food => {
if (food.calories < 300){
state.best_food.push(element)
}
});
```
```javascript
async actionFunction ( context ) {}
```
```javascript
async actionFunction ( { state, commit }, payload ) { }
```
```javascript
async actionFunction ( context, payload1, payload2 ) { }
```
```javascript
async actionFunction ( {context, commit} ) {}
```