Vue 3 Flashcards

1
Q

What is vue

A

Js frame work for buildin ui
Builds on top of standard html css js
provides a declarative and component-based programming model
model–view–viewmodel front end
Connects view and model with two way data binding

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

core features of Vue

A

Declarative Rendering - Reactivity
Vue extends standard HTML with a template syntax that allows us to declaratively describe HTML output based on JavaScript state.

Vue automatically tracks JavaScript state changes and efficiently updates the DOM when changes happen.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

vue capabilites

A

Enhancing static HTML without a build step
Embedding as Web Components on any page
Single-Page Application (SPA)
Fullstack / Server-Side Rendering (SSR)
Jamstack / Static Site Generation (SSG)
Targeting desktop, mobile, WebGL, and even the terminal

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Single-File Components
SFC

A

In most build-tool-enabled Vue projects, we author Vue components using an HTML-like file format called Single-File Component (also known as *.vue files, abbreviated as SFC). A Vue SFC, as the name suggests, encapsulates the component’s logic (JavaScript), template (HTML), and styles (CSS) in a single file

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

API Styles

A

Vue components can be authored in two different API styles: Options API and Composition API.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Options API

A

With Options API, we define a component’s logic using an object of options such as data, methods, and mounted. Properties defined by options are exposed on this inside functions

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Composition API

A

With Composition API, we define a component’s logic using imported API functions. In SFCs, Composition API is typically used with

. The setup attribute is a hint that makes Vue perform compile-time transforms that allow us to use Composition API with less boilerplate. For example, imports and top-level variables / functions declared in 
 are directly usable in the template.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

options vs composition api

A

The Options API is centered around the concept of a “component instance” (this as seen in the example), which typically aligns better with a class-based mental model for users coming from OOP language backgrounds. It is also more beginner-friendly by abstracting away the reactivity details and enforcing code organization via option groups.

The Composition API is centered around declaring reactive state variables directly in a function scope and composing state from multiple functions together to handle complexity. It is more free-form and requires an understanding of how reactivity works in Vue to be used effectively. In return, its flexibility enables more powerful patterns for organizing and reusing logic.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

The application instance

A

Every Vue application starts by creating a new application instance with the createApp function:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

The Root Component

A

The object we are passing into createApp is in fact a component. Every app requires a “root component” that can contain other components as its children.

If you are using Single-File Components, we typically import the root component from another file:

import { createApp } from ‘vue’
// import the root component App from a single-file component.
import App from ‘./App.vue’

const app = createApp(App)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Mounting the App

A

An application instance won’t render anything until its .mount() method is called. It expects a “container” argument, which can either be an actual DOM element or a selector string:

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

App Configurations

A

The application instance exposes a .config object that allows us to configure a few app-level options, for example, defining an app-level error handler that captures errors from all descendant components:

app.config.errorHandler = (err) => {
/* handle error */
}

Make sure to apply all app configurations before mounting the app!

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Template Syntax

A

Vue uses an HTML-based template syntax that allows you to declaratively bind the rendered DOM to the underlying component instance’s data. All Vue templates are syntactically valid HTML that can be parsed by spec-compliant browsers and HTML parsers.

Under the hood, Vue compiles the templates into highly-optimized JavaScript code. Combined with the reactivity system, Vue can intelligently figure out the minimal number of components to re-render and apply the minimal amount of DOM manipulations when the app state changes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

jsx vue

A

If you are familiar with Virtual DOM concepts and prefer the raw power of JavaScript, you can also directly write render functions instead of templates, with optional JSX support. However, do note that they do not enjoy the same level of compile-time optimizations as templates.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Text Interpolation

A

The most basic form of data binding is text interpolation using the “Mustache” syntax (double curly braces):

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

JavaScript expressions

A

In Vue templates, JavaScript expressions can be used in the following positions:

Inside text interpolations (mustaches)
In the attribute value of any Vue directives (special attributes that start with v-)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Expressions Only

A

Each binding can only contain one single expression. An expression is a piece of code that can be evaluated to a value. A simple check is whether it can be used after return

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Calling Functions

A

It is possible to call a component-exposed method inside a binding expression:

Functions called inside binding expressions will be called every time the component updates, so they should not have any side effects, such as changing data or triggering asynchronous operations.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Restricted Globals Access

A

Template expressions are sandboxed and only have access to a restricted list of globals. The list exposes commonly used built-in globals such as Math and Date.

Globals not explicitly included in the list, for example user-attached properties on window, will not be accessible in template expressions. You can, however, explicitly define additional globals for all Vue expressions by adding them to app.config.globalProperties.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Directives

A

Directives are special attributes with the v- prefix. Vue provides a number of built-in directives, including v-html and v-bind which we have introduced above.

Directive attribute values are expected to be single JavaScript expressions (with the exception of v-for, v-on and v-slot, which will be discussed in their respective sections later). A directive’s job is to reactively apply updates to the DOM when the value of its expression changes.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

directive Arguments

A

Some directives can take an “argument”, denoted by a colon after the directive name. For example, the v-bind directive is used to reactively update an HTML attribute:

template
<a> … </a>

<!-- shorthand -->

<a :href=”url”> … </a>

22
Q

Dynamic Arguments

A

It is also possible to use a JavaScript expression in a directive argument by wrapping it with square brackets:

23
Q

Modifiers

A

Modifiers are special postfixes denoted by a dot, which indicate that a directive should be bound in some special way. For example, the .prevent modifier tells the v-on directive to call event.preventDefault() on the triggered event:

24
Q

v-directive shcema

A
25
Q

ref()

A

ref() takes the argument and returns it wrapped within a ref object with a .value property:

we did not need to append .value when using the ref in the template. For

26
Q
<script>

</script>
A

Manually exposing state and methods via setup() can be verbose. Luckily, it can be avoided when using Single-File Components (SFCs).

27
Q

Vue’s reactivity system works.

A

When you use a ref in a template, and change the ref’s value later, Vue automatically detects the change and updates the DOM accordingly. This is made possible with a dependency-tracking based reactivity system. When a component is rendered for the first time, Vue tracks every ref that was used during the render. Later on, when a ref is mutated, it will trigger a re-render for components that are tracking it.

In standard JavaScript, there is no way to detect the access or mutation of plain variables. However, we can intercept the get and set operations of an object’s properties using getter and setter methods.

The .value property gives Vue the opportunity to detect when a ref has been accessed or mutated. Under the hood, Vue performs the tracking in its getter, and performs triggering in its setter. Conceptually, you can think of a ref as an object that looks like this:

// pseudo code, not actual implementation
const myRef = {
_value: 0,
get value() {
track()
return this._value
},
set value(newValue) {
this._value = newValue
trigger()
}
}

28
Q

Deep Reactivity

A

Refs can hold any value type, including deeply nested objects, arrays, or JavaScript built-in data structures like Map.

A ref will make its value deeply reactive. This means you can expect changes to be detected even when you mutate nested objects or arrays:

29
Q

shallow refs.

A

It is also possible to opt-out of deep reactivity with shallow refs. For shallow refs, only .value access is tracked for reactivity. Shallow refs can be used for optimizing performance by avoiding the observation cost of large objects, or in cases where the inner state is managed by an external library.

30
Q

DOM Update Timing

A

When you mutate reactive state, the DOM is updated automatically. However, it should be noted that the DOM updates are not applied synchronously. Instead, Vue buffers them until the “next tick” in the update cycle to ensure that each component updates only once no matter how many state changes you have made.

To wait for the DOM update to complete after a state change, you can use the nextTick() global API:

js
import { nextTick } from ‘vue’

async function increment() {
count.value++
await nextTick()
// Now the DOM is updated
}

31
Q

reactive()

A

There is another way to declare reactive state, with the reactive() API. Unlike a ref which wraps the inner value in a special object, reactive() makes an object itself reactive:

js
import { reactive } from ‘vue’

const state = reactive({ count: 0 })
See also: Typing Reactive

Usage in template:

template
<button @click=”state.count++”>
{{ state.count }}
</button>
Reactive objects are JavaScript Proxies and behave just like normal objects. The difference is that Vue is able to intercept the access and mutation of all properties of a reactive object for reactivity tracking and triggering.

reactive() converts the object deeply: nested objects are also wrapped with reactive() when accessed. It is also called by ref() internally when the ref value is an object. Similar to shallow refs, there is also the shallowReactive() API for opting-out of deep reactivity.

32
Q

Reactive Proxy vs. Original

A

It is important to note that the returned value from reactive() is a Proxy of the original object, which is not equal to the original object:

js
const raw = {}
const proxy = reactive(raw)

// proxy is NOT equal to the original.
console.log(proxy === raw) // false
Only the proxy is reactive - mutating the original object will not trigger updates. Therefore, the best practice when working with Vue’s reactivity system is to exclusively use the proxied versions of your state.

To ensure consistent access to the proxy, calling reactive() on the same object always returns the same proxy, and calling reactive() on an existing proxy also returns that same proxy:

js
// calling reactive() on the same object returns the same proxy
console.log(reactive(raw) === proxy) // true

// calling reactive() on a proxy returns itself
console.log(reactive(proxy) === proxy) // true

33
Q

Limitations of reactive()

A

The reactive() API has a few limitations:

Limited value types: it only works for object types (objects, arrays, and collection types such as Map and Set). It cannot hold primitive types such as string, number or boolean.

Cannot replace entire object: since Vue’s reactivity tracking works over property access, we must always keep the same reference to the reactive object. This means we can’t easily “replace” a reactive object because the reactivity connection to the first reference is lost:

js
let state = reactive({ count: 0 })

// the above reference ({ count: 0 }) is no longer being tracked
// (reactivity connection is lost!)
state = reactive({ count: 1 })
Not destructure-friendly: when we destructure a reactive object’s primitive type property into local variables, or when we pass that property into a function, we will lose the reactivity connection:

js
const state = reactive({ count: 0 })

// count is disconnected from state.count when destructured.
let { count } = state
// does not affect original state
count++

// the function receives a plain number and
// won’t be able to track changes to state.count
// we have to pass the entire object in to retain reactivity
callSomeFunction(state.count)
Due to these limitations, we recommend using ref() as the primary API for declaring reactive state.

34
Q

Computed Properties

A

That’s why for complex logic that includes reactive data, it is recommended to use a computed property.

The computed() function expects to be passed a getter function, and the returned value is a computed ref

35
Q

Computed Caching vs. Methods

A

the difference is that computed properties are cached based on their reactive dependencies.

In comparison, a method invocation will always run the function whenever a re-render happens.

Why do we need caching? Imagine we have an expensive computed property list, which requires looping through a huge array and doing a lot of computations.

36
Q

Writable Computed

A

Computed properties are by default getter-only. If you attempt to assign a new value to a computed property, you will receive a runtime warning. In the rare cases where you need a “writable” computed property, you can create one by providing both a getter and a setter:

vue


import { ref, computed } from 'vue'

const firstName = ref(‘John’)
const lastName = ref(‘Doe’)

const fullName = computed({
// getter
get() {
return firstName.value + ‘ ‘ + lastName.value
},
// setter
set(newValue) {
// Note: we are using destructuring assignment syntax here.
[firstName.value, lastName.value] = newValue.split(‘ ‘)
}
})
</script>

37
Q

Getters should be side-effect free

A

It is important to remember that computed getter functions should only perform pure computation and be free of side effects. For example, don’t mutate other state, make async requests, or mutate the DOM inside a computed getter! Think of a computed property as declaratively describing how to derive a value based on other values - its only responsibility should be computing and returning that value. Later in the guide we will discuss how we can perform side effects in reaction to state changes with watchers

38
Q

Avoid mutating computed value

A

The returned value from a computed property is derived state. Think of it as a temporary snapshot - every time the source state changes, a new snapshot is created. It does not make sense to mutate a snapshot, so a computed return value should be treated as read-only and never be mutated - instead, update the source state it depends on to trigger new computations.

39
Q

Watchers

A

Computed properties allow us to declaratively compute derived values. However, there are cases where we need to perform “side effects” in reaction to state changes - for example, mutating the DOM, or changing another piece of state based on the result of an async operation.

With Composition API, we can use the watch function to trigger a callback whenever a piece of reactive state changes

40
Q

lifecycle hooks view

A

onMounted()
onUpdated()
onUnmounted()
onBeforeMount()
onBeforeUpdate
onBeforeUnmount()

41
Q

onMounted

A

Registers a callback to be called after the component has been mounted.

A component is considered mounted after:

All of its synchronous child components have been mounted (does not include async components or components inside <Suspense> trees).</Suspense>

Its own DOM tree has been created and inserted into the parent container. Note it only guarantees that the component’s DOM tree is in-document if the application’s root container is also in-document.

This hook is typically used for performing side effects that need access to the component’s rendered DOM, or for limiting DOM-related code to the client in a server-rendered application.

This hook is not called during server-side rendering.

42
Q

onUpdated()

A

Registers a callback to be called after the component has updated its DOM tree due to a reactive state change.

A parent component’s updated hook is called after that of its child components.

This hook is called after any DOM update of the component, which can be caused by different state changes, because multiple state changes can be batched into a single render cycle for performance reasons. If you need to access the updated DOM after a specific state change, use nextTick() instead.

This hook is not called during server-side rendering.

WARNING

Do not mutate component state in the updated hook - this will likely lead to an infinite update loop!

43
Q

onUnmounted

A

Registers a callback to be called after the component has been unmounted.

Type

ts
function onUnmounted(callback: () => void): void
Details

A component is considered unmounted after:

All of its child components have been unmounted.

All of its associated reactive effects (render effect and computed / watchers created during setup()) have been stopped.

Use this hook to clean up manually created side effects such as timers, DOM event listeners or server connections.

This hook is not called during server-side rendering.

44
Q

onBeforeMount()

A

Registers a hook to be called right before the component is to be mounted.

Type

ts
function onBeforeMount(callback: () => void): void
Details

When this hook is called, the component has finished setting up its reactive state, but no DOM nodes have been created yet. It is about to execute its DOM render effect for the first time.

This hook is not called during server-side rendering.

45
Q

onBeforeUpdate

A

Registers a hook to be called right before the component is about to update its DOM tree due to a reactive state change.

Type

ts
function onBeforeUpdate(callback: () => void): void
Details

This hook can be used to access the DOM state before Vue updates the DOM. It is also safe to modify component state inside this hook.

This hook is not called during server-side rendering.

46
Q

onErrorCaptured()

A

Registers a hook to be called when an error propagating from a descendant component has been captured.

Type

ts
function onErrorCaptured(callback: ErrorCapturedHook): void

type ErrorCapturedHook = (
err: unknown,
instance: ComponentPublicInstance | null,
info: string
) => boolean | void
Details

Errors can be captured from the following sources:

Component renders
Event handlers
Lifecycle hooks
setup() function
Watchers
Custom directive hooks
Transition hooks
The hook receives three arguments: the error, the component instance that triggered the error, and an information string specifying the error source type.

TIP

In production, the 3rd argument (info) will be a shortened code instead of the full information string. You can find the code to string mapping in the Production Error Code Reference.

You can modify component state in errorCaptured() to display an error state to the user. However, it is important that the error state should not render the original content that caused the error; otherwise the component will be thrown into an infinite render loop.

The hook can return false to stop the error from propagating further. See error propagation details below.

47
Q

onActivated()

A

Registers a callback to be called after the component instance is inserted into the DOM as part of a tree cached by <KeepAlive>.</KeepAlive>

This hook is not called during server-side rendering.

Type

ts
function onActivated(callback: () => void): void
See also Guide - Lifecycle of Cached Instance

48
Q

onDeactivated

A

Registers a callback to be called after the component instance is removed from the DOM as part of a tree cached by <KeepAlive>.</KeepAlive>

This hook is not called during server-side rendering.

Type

ts
function onDeactivated(callback: () => void): void
See also Guide - Lifecycle of Cached Instance

49
Q

onServerPrefetch()

A

Registers an async function to be resolved before the component instance is to be rendered on the server.

Type

ts
function onServerPrefetch(callback: () => Promise<any>): void
Details</any>

If the callback returns a Promise, the server renderer will wait until the Promise is resolved before rendering the component.

This hook is only called during server-side rendering can be used to perform server-only data fetching.

50
Q

Dependency Injection

A

provide inject

51
Q

Prop Drilling

A

Usually, when we need to pass data from the parent to a child component, we use props. However, imagine the case where we have a large component tree, and a deeply nested component needs something from a distant ancestor component. With only props, we would have to pass the same prop across the entire parent chain:

We can solve props drilling with provide and inject. A parent component can serve as a dependency provider for all its descendants. Any component in the descendant tree, regardless of how deep it is, can inject dependencies provided by components up in its parent chain.