# Perguntas essenciais de Vue.js: 25 perguntas para conquistar a vaga
> Prepare-se para entrevistas de Vue.js com estas 25 perguntas essenciais. Da reatividade aos composables, domine os conceitos-chave para a próxima entrevista.
- Published: 2026-02-05
- Updated: 2026-04-27
- Author: SharpSkill
- Tags: vue.js, interview, frontend, javascript, technical questions
- Reading time: 15 min
---
As entrevistas de Vue.js avaliam muito mais do que a sintaxe do framework. Os recrutadores querem entender o domínio do sistema de reatividade, a organização do código com a Composition API e a capacidade de resolver desafios reais de performance e arquitetura.
> **Dica de preparação**
>
> Cada pergunta inclui uma resposta detalhada e exemplos de código. Para entrevistas técnicas, vale a pena praticar explicando os conceitos em voz alta, como em uma entrevista real.
## Perguntas fundamentais de Vue.js
### 1. Qual é a diferença entre ref e reactive no Vue 3?
Esta pergunta avalia a compreensão do sistema de reatividade, peça fundamental do Vue 3. A diferença principal está nos tipos de dados manipulados e na sintaxe de acesso.
`ref` cria uma referência reativa para valores primitivos (string, number, boolean) e exige `.value` para acessar o valor no script. `reactive` cria um proxy reativo para objetos e permite acesso direto às propriedades.
```javascript
// Exemplo comparativo ref vs reactive
import { ref, reactive } from 'vue'
// ref: for primitives
// Requires .value in the script
const count = ref(0)
count.value++ // Access with .value
// reactive: for complex objects
// Direct property access
const user = reactive({
name: 'Alice',
age: 25
})
user.age++ // No .value needed
// Warning: reactive loses reactivity if reassigned
// user = { name: 'Bob', age: 30 } // ❌ Breaks reactivity
Object.assign(user, { name: 'Bob', age: 30 }) // ✅ Correct
```
Regra geral: usar `ref` para valores simples e `reactive` para objetos estruturados com várias propriedades relacionadas.
### 2. Como funciona o sistema de reatividade do Vue 3?
O Vue 3 usa Proxies do JavaScript (ES6) para interceptar operações em objetos reativos. Diferente do Vue 2, que usava `Object.defineProperty`, esta abordagem detecta dinamicamente a adição e remoção de propriedades.
```javascript
// Simplified demonstration of the reactivity principle
// Vue uses Proxies to track dependencies
const handler = {
// Intercept reading
get(target, key, receiver) {
track(target, key) // Register the dependency
return Reflect.get(target, key, receiver)
},
// Intercept writing
set(target, key, value, receiver) {
const result = Reflect.set(target, key, value, receiver)
trigger(target, key) // Trigger updates
return result
}
}
// Creating a reactive proxy
const reactiveObject = new Proxy(originalObject, handler)
```
Entre as vantagens do Proxy estão: detecção de novas propriedades, suporte a Map e Set, e melhor performance em objetos grandes.
### 3. Explique a diferença entre computed e watch
`computed` e `watch` atendem a necessidades diferentes na gestão da reatividade.
**Computed**: calcula um valor derivado a partir de outros dados reativos. Os valores ficam em cache e só são recalculados quando as dependências mudam. Ideal para transformações de dados.
**Watch**: executa efeitos colaterais em resposta a mudanças. Útil para chamadas de API, interações com o DOM ou operações assíncronas.
```javascript
// Computed vs watch comparison
import { ref, computed, watch } from 'vue'
const firstName = ref('John')
const lastName = ref('Doe')
// computed: derived value with cache
// Recalculates only if firstName or lastName changes
const fullName = computed(() => {
console.log('Computing full name') // Called only once
return `${firstName.value} ${lastName.value}`
})
// Multiple accesses = single execution (cached)
console.log(fullName.value) // "John Doe"
console.log(fullName.value) // No recalculation
// watch: side effect without cache
// Executed on every change
watch(firstName, async (newName, oldName) => {
// Side effect: API call
await saveToServer({ firstName: newName })
console.log(`Name changed from ${oldName} to ${newName}`)
})
```
### 4. O que é o Virtual DOM e como o Vue o utiliza?
O Virtual DOM é uma representação leve do DOM real em JavaScript. O Vue mantém uma árvore virtual em memória e calcula as diferenças (diffing) entre o estado anterior e o novo para aplicar ao DOM real apenas as mudanças necessárias.
```javascript
// Conceptual representation of the Virtual DOM
// Vue creates this structure internally
const vnode = {
type: 'div',
props: {
class: 'container',
id: 'app'
},
children: [
{
type: 'h1',
props: {},
children: 'Title'
},
{
type: 'p',
props: {},
children: 'Paragraph content'
}
]
}
// When changes occur, Vue compares vnodes
// and updates only the modified elements
```
As otimizações do Vue 3 incluem: hoisting de nós estáticos, patch flags para identificar o tipo de mudança e tree-shaking no compilador.
### 5. Como gerenciar a comunicação entre componentes sem relação direta?
Existem vários padrões para comunicar componentes que não compartilham relação direta de pai e filho.
```javascript
// Solution 1: Event Bus (small applications)
// eventBus.js
import { ref } from 'vue'
const bus = ref(new Map())
export function useEventBus() {
// Emit an event
const emit = (event, payload) => {
const callbacks = bus.value.get(event) || []
callbacks.forEach(cb => cb(payload))
}
// Listen to an event
const on = (event, callback) => {
if (!bus.value.has(event)) {
bus.value.set(event, [])
}
bus.value.get(event).push(callback)
}
return { emit, on }
}
```
```javascript
// Solution 2: Provide/Inject for nested components
// Ancestor
import { provide, ref } from 'vue'
const sharedState = ref('shared value')
provide('stateKey', sharedState)
// Descendant (any level)
import { inject } from 'vue'
const state = inject('stateKey')
```
Para aplicações mais complexas, o Pinia continua sendo a solução recomendada para gerenciar o estado global.
## Perguntas sobre a Composition API
### 6. Quais as vantagens da Composition API frente à Options API?
A Composition API oferece várias vantagens estruturais sobre a Options API tradicional.
**Organização por funcionalidade**: o código relacionado à mesma feature fica agrupado, ao contrário da Options API, que separa por tipo (data, methods, computed).
**Reutilização via composables**: extração simples da lógica em funções reutilizáveis.
**Melhor suporte ao TypeScript**: inferência de tipos natural, sem decoradores.
```javascript
// Options API: code fragmented by type
export default {
data() {
return {
searchQuery: '',
results: []
}
},
computed: {
hasResults() {
return this.results.length > 0
}
},
methods: {
async search() {
this.results = await fetchResults(this.searchQuery)
}
},
watch: {
searchQuery: 'search'
}
}
// Composition API: code grouped by feature
import { ref, computed, watch } from 'vue'
export function useSearch() {
const searchQuery = ref('')
const results = ref([])
const hasResults = computed(() => results.value.length > 0)
const search = async () => {
results.value = await fetchResults(searchQuery.value)
}
watch(searchQuery, search)
return { searchQuery, results, hasResults, search }
}
```
### 7. Como criar um composable reutilizável?
Composables são funções que encapsulam lógica reativa. As convenções incluem: prefixo `use`, retorno de um objeto com estado e métodos, e tratamento do cleanup.
```javascript
// composables/useLocalStorage.js
import { ref, watch } from 'vue'
// Composable to synchronize state with localStorage
export function useLocalStorage(key, defaultValue) {
// Retrieve initial value from localStorage
const storedValue = localStorage.getItem(key)
const data = ref(
storedValue ? JSON.parse(storedValue) : defaultValue
)
// Synchronize changes to localStorage
watch(
data,
(newValue) => {
if (newValue === null) {
localStorage.removeItem(key)
} else {
localStorage.setItem(key, JSON.stringify(newValue))
}
},
{ deep: true } // Observe nested objects
)
return data
}
// Usage in a component
const theme = useLocalStorage('theme', 'light')
const userPrefs = useLocalStorage('prefs', { notifications: true })
```
> **Convenção de nomes**
>
> Composables seguem a convenção `useXxx` para indicar seu caráter reutilizável. Essa convenção melhora a legibilidade e facilita a identificação das dependências reativas.
### 8. Explique watchEffect frente a watch
`watchEffect` e `watch` reagem a mudanças, mas com abordagens diferentes.
**watchEffect**: executa imediatamente e roda novamente de forma automática quando suas dependências reativas mudam. O rastreio das dependências é automático.
**watch**: observa fontes específicas e fornece valores antigos e novos. Maior controle sobre quando dispara.
```javascript
// watchEffect vs watch comparison
import { ref, watch, watchEffect } from 'vue'
const userId = ref(1)
const userData = ref(null)
// watchEffect: automatic tracking
// Runs immediately
watchEffect(async () => {
// userId is automatically tracked
const response = await fetch(`/api/users/${userId.value}`)
userData.value = await response.json()
})
// watch: explicit sources with old values
watch(userId, async (newId, oldId) => {
console.log(`User changed from ${oldId} to ${newId}`)
const response = await fetch(`/api/users/${newId}`)
userData.value = await response.json()
}, {
immediate: true // Run immediately like watchEffect
})
// watchEffect with cleanup
watchEffect((onCleanup) => {
const controller = new AbortController()
fetch(`/api/users/${userId.value}`, {
signal: controller.signal
}).then(/* ... */)
// Cleanup: cancel previous request
onCleanup(() => controller.abort())
})
```
### 9. Como gerenciar props com TypeScript no script setup?
A sintaxe `
```
## Perguntas de performance
### 10. Quais técnicas de otimização de performance vale conhecer?
O Vue 3 oferece vários mecanismos para otimizar a performance.
```javascript
// 1. v-once: single render for static content
// 2. v-memo: conditional memoization
{{ item.name }}
// 3. shallowRef/shallowReactive: shallow reactivity
import { shallowRef, triggerRef } from 'vue'
// Only tracks ref replacement, not internal mutations
const largeList = shallowRef([/* thousands of elements */])
// Force update after mutation
largeList.value.push(newItem)
triggerRef(largeList) // Manually trigger re-render
```
```javascript
// 4. Async components for code-splitting
import { defineAsyncComponent } from 'vue'
const HeavyComponent = defineAsyncComponent({
loader: () => import('./HeavyComponent.vue'),
loadingComponent: LoadingSpinner,
delay: 200, // Delay before showing loading
errorComponent: ErrorDisplay,
timeout: 3000
})
// 5. KeepAlive for component caching
```
### 11. Como evitar re-renders desnecessários?
Re-renders desnecessários impactam a performance. Algumas estratégias ajudam a minimizá-los.
```javascript
// Problem: function created on each render
handleClick(item.id)" />
// Solution: use a method or ref
```
```javascript
// Using computed for expensive calculations
import { computed } from 'vue'
// ❌ Recalculated on every render
const getFilteredItems = () => {
return items.value.filter(/* complex logic */)
}
// ✅ Cached, recalculated only if items changes
const filteredItems = computed(() => {
return items.value.filter(/* complex logic */)
})
```
### 12. Explique o lazy loading de componentes e rotas
O lazy loading permite carregar código sob demanda, reduzindo o tamanho do bundle inicial.
```javascript
// router/index.js
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
// Immediate loading (main bundle)
component: () => import('@/views/Home.vue')
},
{
path: '/dashboard',
// Separate chunk with custom name
component: () => import(
/* webpackChunkName: "dashboard" */
'@/views/Dashboard.vue'
),
// Lazy loading child routes
children: [
{
path: 'analytics',
component: () => import('@/views/Analytics.vue')
}
]
},
{
path: '/admin',
// Prefetch on link hover
component: () => import('@/views/Admin.vue'),
meta: { prefetch: true }
}
]
})
export default router
```
## Perguntas sobre Vue Router
### 13. Como proteger rotas com guards?
Os navigation guards permitem controlar o acesso às rotas.
```javascript
// router/index.js
import { createRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
const router = createRouter({
routes: [
{
path: '/dashboard',
component: Dashboard,
meta: { requiresAuth: true, roles: ['admin', 'user'] }
}
]
})
// Global guard: checks authentication
router.beforeEach(async (to, from, next) => {
const auth = useAuthStore()
// Public route
if (!to.meta.requiresAuth) {
return next()
}
// Check authentication
if (!auth.isAuthenticated) {
return next({
path: '/login',
query: { redirect: to.fullPath }
})
}
// Check roles if specified
if (to.meta.roles && !to.meta.roles.includes(auth.user.role)) {
return next('/unauthorized')
}
next()
})
// Component-level guard
export default {
beforeRouteEnter(to, from, next) {
// No access to this here
next(vm => {
// Access component instance via vm
vm.loadData()
})
},
beforeRouteLeave(to, from, next) {
// Confirm before leaving if form modified
if (this.hasUnsavedChanges) {
const answer = confirm('Leave without saving?')
next(answer)
} else {
next()
}
}
}
```
### 14. Como passar props para as rotas?
O Vue Router permite desacoplar componentes dos parâmetros de rota.
```javascript
// Route configuration with props
const routes = [
{
path: '/user/:id',
component: UserProfile,
// Boolean mode: passes params as props
props: true
},
{
path: '/search',
component: SearchResults,
// Function mode: custom transformation
props: (route) => ({
query: route.query.q,
page: parseInt(route.query.page) || 1,
filters: route.query.filters?.split(',') || []
})
},
{
path: '/static',
component: StaticPage,
// Object mode: static props
props: { sidebar: true, theme: 'dark' }
}
]
```
```javascript
// UserProfile.vue
// SearchResults.vue
```
## Perguntas sobre Pinia e gerenciamento de estado
### 15. Quais as diferenças entre Pinia e Vuex?
Pinia é o gerenciador de estado oficial do Vue 3, substituindo o Vuex com uma API simplificada.
| Característica | Vuex | Pinia |
|---------|------|-------|
| Mutations | Obrigatórias | Não necessárias |
| Módulos | Configuração complexa | Stores independentes |
| TypeScript | Suporte limitado | Nativo e completo |
| API | Options | Composition + Options |
| DevTools | Suporte | Suporte completo |
```javascript
// Pinia Store with Composition API
import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
export const useCartStore = defineStore('cart', () => {
// State
const items = ref([])
const discountCode = ref(null)
// Getters (computed)
const totalItems = computed(() =>
items.value.reduce((sum, item) => sum + item.quantity, 0)
)
const totalPrice = computed(() => {
const subtotal = items.value.reduce(
(sum, item) => sum + item.price * item.quantity, 0
)
return discountCode.value ? subtotal * 0.9 : subtotal
})
// Actions (direct functions)
function addItem(product) {
const existing = items.value.find(i => i.id === product.id)
if (existing) {
existing.quantity++
} else {
items.value.push({ ...product, quantity: 1 })
}
}
function removeItem(productId) {
const index = items.value.findIndex(i => i.id === productId)
if (index > -1) {
items.value.splice(index, 1)
}
}
async function checkout() {
const response = await api.createOrder(items.value)
items.value = []
return response
}
return {
items, discountCode,
totalItems, totalPrice,
addItem, removeItem, checkout
}
})
```
### 16. Como persistir o estado de uma store Pinia?
A persistência permite manter o estado entre as sessões do usuário.
```javascript
// plugins/piniaPersistedState.js
import { watch } from 'vue'
export function createPersistedState(options = {}) {
const {
key = 'pinia',
storage = localStorage,
paths = null
} = options
return ({ store }) => {
// Restore state on startup
const savedState = storage.getItem(`${key}-${store.$id}`)
if (savedState) {
store.$patch(JSON.parse(savedState))
}
// Persist changes
watch(
() => store.$state,
(state) => {
const toSave = paths
? paths.reduce((acc, path) => {
acc[path] = state[path]
return acc
}, {})
: state
storage.setItem(
`${key}-${store.$id}`,
JSON.stringify(toSave)
)
},
{ deep: true }
)
}
}
// main.js
import { createPinia } from 'pinia'
import { createPersistedState } from './plugins/piniaPersistedState'
const pinia = createPinia()
pinia.use(createPersistedState({
key: 'app-state',
paths: ['user', 'preferences'] // Persist only these keys
}))
```
> **Dados sensíveis**
>
> Vale evitar a persistência de dados sensíveis (tokens, senhas) no localStorage. Para tokens de autenticação, o ideal são cookies httpOnly.
## Perguntas avançadas
### 17. Como implementar um sistema de plugins no Vue?
Plugins permitem estender o Vue com funcionalidades globais.
```javascript
// plugins/analyticsPlugin.js
export const AnalyticsPlugin = {
install(app, options = {}) {
const { trackingId, debug = false } = options
// Global injection available in all components
const analytics = {
trackEvent(category, action, label) {
if (debug) {
console.log('Analytics:', { category, action, label })
}
// Logic to send to analytics service
window.gtag?.('event', action, {
event_category: category,
event_label: label
})
},
trackPage(path) {
window.gtag?.('config', trackingId, { page_path: path })
}
}
// Make available via inject
app.provide('analytics', analytics)
// Add global property (discouraged in Composition API)
app.config.globalProperties.$analytics = analytics
// Custom directive for click tracking
app.directive('track', {
mounted(el, binding) {
el.addEventListener('click', () => {
analytics.trackEvent('click', binding.value, el.textContent)
})
}
})
// Automatic route change tracking
app.mixin({
mounted() {
if (this.$route) {
analytics.trackPage(this.$route.path)
}
}
})
}
}
// main.js
import { AnalyticsPlugin } from './plugins/analyticsPlugin'
app.use(AnalyticsPlugin, {
trackingId: 'UA-XXXXX-X',
debug: import.meta.env.DEV
})
```
### 18. Explique as Render Functions e sua utilidade
Render functions oferecem controle total sobre a renderização, úteis para componentes muito dinâmicos.
```javascript
// components/DynamicHeading.js
import { h } from 'vue'
// Functional component with render function
export const DynamicHeading = {
props: {
level: {
type: Number,
default: 1,
validator: (v) => v >= 1 && v <= 6
}
},
setup(props, { slots }) {
// h() creates a vnode
// Arguments: type, props, children
return () => h(
`h${props.level}`,
{ class: 'dynamic-heading' },
slots.default?.()
)
}
}
// Component with complex conditional logic
export const ConditionalWrapper = {
props: ['condition', 'wrapper'],
setup(props, { slots }) {
return () => {
if (props.condition) {
return h(props.wrapper, null, slots.default?.())
}
return slots.default?.()
}
}
}
// Usage
Level 2 Title
Conditional content
```
### 19. Como testar componentes Vue com Vitest?
Os testes unitários validam o comportamento isolado dos componentes.
```javascript
// components/__tests__/Counter.spec.js
import { describe, it, expect, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import Counter from '../Counter.vue'
describe('Counter', () => {
it('displays the initial value', () => {
const wrapper = mount(Counter, {
props: { initialValue: 5 }
})
expect(wrapper.text()).toContain('5')
})
it('increments the value on click', async () => {
const wrapper = mount(Counter)
await wrapper.find('button.increment').trigger('click')
expect(wrapper.text()).toContain('1')
})
it('emits an event when changed', async () => {
const wrapper = mount(Counter)
await wrapper.find('button.increment').trigger('click')
expect(wrapper.emitted('change')).toBeTruthy()
expect(wrapper.emitted('change')[0]).toEqual([1])
})
it('calls the service on submit', async () => {
const mockSubmit = vi.fn()
const wrapper = mount(Counter, {
global: {
provide: {
submitService: mockSubmit
}
}
})
await wrapper.find('form').trigger('submit')
expect(mockSubmit).toHaveBeenCalled()
})
})
```
### 20. Como tratar erros de forma global no Vue?
O Vue 3 oferece vários mecanismos para capturar e tratar erros.
```javascript
// main.js
import { createApp } from 'vue'
const app = createApp(App)
// Global handler for component errors
app.config.errorHandler = (err, instance, info) => {
// err: the error
// instance: the component instance
// info: string describing where the error occurred
console.error('Vue error:', err)
console.error('Component:', instance?.$options?.name)
console.error('Info:', info)
// Send to monitoring service
errorTracker.captureException(err, {
component: instance?.$options?.name,
info
})
}
// Handler for warnings (dev only)
app.config.warnHandler = (msg, instance, trace) => {
console.warn('Vue warning:', msg)
}
```
```javascript
// ErrorBoundary component
An error occurred
{{ error.message }}
```
## Perguntas sobre boas práticas
### 21. Quais convenções de nomes seguir no Vue?
As convenções de nomes melhoram a legibilidade e a manutenção do código.
```javascript
// Component naming
// PascalCase for files and names
// BaseButton.vue, AppHeader.vue, TheNavbar.vue
// Props: camelCase in JS, kebab-case in template
defineProps<{
userName: string // JS
isActive: boolean // JS
}>()
//
// Events: camelCase with action prefix
const emit = defineEmits<{
(e: 'updateValue', value: string): void // ✅
(e: 'submit'): void // ✅
(e: 'value-updated'): void // ❌ Avoid
}>()
// Composables: use prefix
// useAuth.js, useFetch.js, useLocalStorage.js
// Pinia stores: use prefix + Store suffix
// useUserStore, useCartStore, useSettingsStore
// Constants: SCREAMING_SNAKE_CASE
const MAX_RETRY_COUNT = 3
const API_BASE_URL = '/api/v1'
```
### 22. Como estruturar um projeto Vue de grande escala?
Uma estrutura modular facilita a navegação e a manutenção.
```
src/
├── assets/ # Static files
├── components/
│ ├── ui/ # Generic components (Button, Modal)
│ └── common/ # Reusable business components
├── composables/ # Reusable logic
│ ├── useAuth.js
│ └── useFetch.js
├── layouts/ # Page layouts
│ ├── DefaultLayout.vue
│ └── AuthLayout.vue
├── modules/ # Functional modules
│ ├── auth/
│ │ ├── components/
│ │ ├── composables/
│ │ ├── stores/
│ │ └── views/
│ └── dashboard/
├── plugins/ # Vue plugins
├── router/
│ ├── index.js
│ └── guards.js
├── stores/ # Global Pinia stores
├── types/ # TypeScript types
├── utils/ # Pure utilities
└── views/ # Pages/Routes
```
### 23. Quando usar v-if frente a v-show?
A escolha entre `v-if` e `v-show` depende da frequência de toggle.
```javascript
// v-if: low initial cost, expensive toggle
// Removes/adds element from DOM
// Ideal for: rarely modified conditions
// v-show: higher initial cost, fast toggle
// Uses display: none
// Ideal for: frequent toggles
Contextual information
{{ content }}
```
### 24. Como otimizar listas com v-for?
A otimização de listas é crítica para a performance com muitos elementos.
```javascript
// Always use :key with a unique stable identifier
{{ item.name }}
{{ item.name }}
// Filtering and sorting: use computed
// Virtualization for very long lists
{{ item.data.name }}
```
### 25. Explique o padrão Renderless component
Componentes renderless encapsulam a lógica sem impor estrutura HTML.
```javascript
// components/MouseTracker.vue
```
```javascript
// Usage: full control over rendering
Position: {{ x }}, {{ y }}
```
Esse padrão separa por completo a lógica da apresentação, maximizando a reutilização.
## Conclusão
Estas 25 perguntas cobrem os conceitos essenciais avaliados em entrevistas de Vue.js:
- ✅ **Reatividade**: `ref`, `reactive`, `computed`, `watch`
- ✅ **Composition API**: composables, `script setup`, TypeScript
- ✅ **Performance**: lazy loading, virtualização, otimizações
- ✅ **Vue Router**: guards, props, navegação
- ✅ **Pinia**: stores, persistência, ações assíncronas
- ✅ **Boas práticas**: estrutura, convenções, padrões avançados
Uma preparação eficaz combina compreensão teórica com prática de código. Cada conceito tratado aqui pode dar origem a perguntas de aprofundamento durante a entrevista.
---
Source: SharpSkill (https://sharpskill.dev), tech interview preparation for your real stack.
HTML version of this page: https://sharpskill.dev/pt/blog/vue-nuxt/essential-vuejs-interview-questions