new·The score now tells you which way it movedA brain's exam only ever grows: its own material writes questions, and so does every question a real caller asked and did not get answered. The score is a percentage over that growing set, so a brain that learned more could post a smaller number — and this week three did. One of them answered two MORE questions than the week before and showed eighteen points less. Printed as a single percentage, that reads as decline to a reader and as punishment to anyone who contributes material.all news →
mozg.beta
Sign in

Vue · Tutorial · all subjects

tutorial/component-basics

80 notes in this subject, read out of this brain and free to use. This is page 1 of 2.

Using a child component in template with SFC

After importing and registering a child component in a single-file component, use it in the template as a self-closing tag with the component name: <ChildComp />

Registering a component in Options API

In Options API, after importing a child component, register it using the components option in the export default object. Use object property shorthand: export default { components: { ChildComp } }

Importing a child component in Composition API

In Composition API with single-file components, import a child component using the import statement at the top of the script: import ChildComp from './ChildComp.vue'

Registering a component with createApp

When using createApp in the HTML mode, register a child component by importing it and then passing it to the components option in the createApp configuration object: createApp({ components: { ChildComp } })

Using kebab-cased component names in DOM templates

When writing templates directly in the DOM (HTML mode), browser parsing rules are case-insensitive for tag names. Therefore, child components must be referenced using kebab-cased names: <child-comp></child-comp> instead of <ChildComp />

Parent and child components structure

Real Vue applications are typically created with nested components. A parent component can render another component in its template as a child component.

defineProps is a compile-time macro

defineProps() is a compile-time macro in Vue's Composition API with <script setup> and does not need to be imported. It is processed by the compiler at build time.

Passing props from parent to child component

The parent can pass a prop to the child component using attribute syntax. To pass a dynamic value, use the v-bind syntax with a colon. Example in SFC: <ChildComp :msg="greeting" />. In HTML mode: <child-comp :msg="greeting"></child-comp>.

Limitations of compiler macros like script setup

defineProps() is a compile-time macro and has limitations as a compiler macro for <script setup>.

What is a prop in Vue

A prop is input passed from a parent component to a child component. The child component must declare which props it accepts, and once declared, the prop can be used in the child component's template and accessed in JavaScript code.

Declaring props with defineProps in Composition API with script setup

In a Vue SFC using Composition API with <script setup>, declare props using the defineProps() compile-time macro. Example: const props = defineProps({ msg: String }). The defineProps() macro does not need to be imported. Once declared, the prop can be used in the template and accessed in JavaScript via the returned object.

Declaring props with setup function in Composition API

In a child component using Composition API with a setup() function, declare props in the props object of the default export: export default { props: { msg: String }, setup(props) { // access props.msg } }. The received props are passed to setup() as the first argument.

Declaring props in Options API

In a child component using Options API, declare props in the props object of the default export: export default { props: { msg: String } }. Once declared, the prop is exposed on 'this' and can be used in the child component's template.

What is a prop in Vue

A prop is a way to pass data from a parent component to a child component. Props are declared using either the props option in the Options API or the defineProps() macro in the Composition API with <script setup>. Props are read-only and flow one-way from parent to child. Events (emits) are the corresponding mechanism for child components to send data back to parents.

defineEmits in Composition API with <script setup>

In the Composition API with <script setup>, use defineEmits() to declare which events a component can emit. Pass an array of event names as strings. Example: const emit = defineEmits(['response']). The emit function returned can then be called to emit events to the parent.

Emitting events with emit() function

In Composition API <script setup>, call emit() with the event name as the first argument and any additional arguments as subsequent parameters. Example: emit('response', 'hello from child'). These additional arguments are passed to the parent's event handler.

emits declaration in Composition API setup function

In Composition API without <script setup>, declare emitted events using the emits option with an array of event names: emits: ['response']. Access the emit function through destructuring the second parameter of setup: setup(props, { emit }). Then call emit('response', 'hello from child') to emit events.

emits declaration in Options API

In the Options API, declare emitted events using the emits option with an array of event names: emits: ['response']. Emit events using this.$emit() within component methods or lifecycle hooks. Example: this.$emit('response', 'hello from child').

Listening to child component events with v-on

In a parent component, listen to child-emitted events using the v-on directive (or @ shorthand) on the child component element. The handler receives any additional arguments passed by the child's emit call. Example: <ChildComp @response="(msg) => childMsg = msg" />. This assigns the emitted message to local state.

Parent listening to child events with v-on in HTML mode

In HTML mode, listen to child-emitted events using v-on or @ on the child component element. Example: <child-comp @response="(msg) => childMsg = msg"></child-comp>. The handler receives the emitted argument and can assign it to local state.

Passing template fragments to child components with slots

Parent components can pass template fragments to child components using slots. In the parent, content is placed between the opening and closing tags of the child component (e.g., <ChildComp>This is some slot content!</ChildComp> in SFC mode or <child-comp>This is some slot content!</child-comp> in HTML mode).

Rendering slot content in child component

The child component renders slot content passed from the parent using the <slot/> element (or <slot></slot>) as an outlet in the child template.

Fallback content in slots

Content placed inside the <slot> element serves as fallback content. The fallback content is displayed only if the parent component does not pass down any slot content to the child.

Slots definition compared to props

In addition to passing data via props, parent components can also pass down template fragments to child components via slots, providing another mechanism for parent-child communication.

Reactive state in Composition API with <script setup>

Reactive state declared in the component's <script setup> block can be used directly in the template.

Other lifecycle hooks in Options API

In addition to mounted, the Options API provides other lifecycle hooks such as created and updated.

onMounted syntax in Composition API

In the Composition API, the onMounted hook is called with a callback function that runs after the component is mounted. Example: onMounted(() => { // component is now mounted. })

mounted lifecycle option in Options API

In the Options API, the mounted option is an object property that defines code to run after the component is mounted. Example: mounted() { // component is now mounted. }

Definition of lifecycle hook

A lifecycle hook allows you to register a callback to be called at certain times of the component's lifecycle.

Other lifecycle hooks in Composition API

In addition to onMounted, the Composition API provides other lifecycle hooks such as onUpdated and onUnmounted.

Template ref syntax in template

A template ref is a reference to an element in the template. It is declared using the special ref attribute on the element. For example: <p ref="pElementRef">hello</p>

Template ref initialization in Composition API

In the Composition API, a template ref must be declared with the ref() function and initialized with null, because the element does not exist yet when setup() executes. The matching name must be used between the template and the script. Example: const pElementRef = ref(null)

Template ref timing in Composition API

Template refs are only accessible after the component is mounted. The value is accessed via pElementRef.value in Composition API.

Template ref in Options API

In the Options API, template refs are exposed on this.$refs with the property name matching the ref attribute. They are only accessible after the component is mounted.

onMounted lifecycle hook import

The onMounted function must be imported from 'vue' to use it in the Composition API: import { onMounted } from 'vue'

computed() function in Composition API

In Composition API, import `computed` from 'vue' and create a computed ref by calling computed() with a callback function. The callback accesses reactive data via `.value` property. Example: const filteredTodos = computed(() => { return filtered todos based on todos.value & hideCompleted.value }). The computed ref must be returned from setup() to be accessible in the template.

Computed property caching and reactivity

A computed property automatically tracks other reactive state used in its computation as dependencies. It caches the result and automatically updates the cached value when any of its dependencies change.

Using computed property in v-for

In a template, use a computed property name directly in v-for the same way as a regular data property. For example, change `<li v-for="todo in todos">` to `<li v-for="todo in filteredTodos">` to iterate over the computed filtered list.

Computed property in Options API

In Options API, declare a computed property using the `computed` option. Inside, define methods that return computed values based on other properties. Access component state via `this`. Example: computed: { filteredTodos() { return filtered todos based on `this.hideCompleted` } }

defineExpose example

Example: const a = 1; const b = ref(2); defineExpose({a, b}) exposes these as { a: number, b: number } when retrieved via template refs.

defineExpose for exposing component properties

Components using `<script setup>` are closed by default; the public instance retrieved via template refs or $parent chains will not expose bindings declared inside `<script setup>`. Use the `defineExpose` compiler macro to explicitly expose properties. Refs are automatically unwrapped in the exposed instance.

defineSlots for TypeScript slot type hints

`defineSlots()` is available in Vue 3.3+ and provides type hints to IDEs for slot name and props type checking. It accepts only a type parameter (no runtime arguments). The type parameter should be a type literal where property keys are slot names and value types are slot functions. The function's first argument is the props the slot expects to receive.

defineSlots example

Example in <script setup lang="ts">: const slots = defineSlots<{default(props: { msg: string }): any}>(). This provides type hints for a default slot that receives props with a msg string property.

Component usage in <script setup> templates

In `<script setup>`, imported components can be used directly as custom component tag names in templates without registration. PascalCase component tags are strongly recommended for consistency and to differentiate from native custom elements. The kebab-case equivalent also works but is not recommended.

Dynamic components in <script setup>

Since components are referenced as variables in `<script setup>`, use dynamic `:is` binding for dynamic components. Example: <component :is="someCondition ? Foo : Bar" /> allows components to be used as variables in ternary expressions.

Recursive components in <script setup>

An SFC can implicitly refer to itself via its filename. A file named `FooBar.vue` can refer to itself as `<FooBar/>` in its template. This has lower priority than imported components. If a named import conflicts with the component's inferred name, alias the import: import { FooBar as FooBarChild } from './components'

Namespaced components with dot notation

Components can use tags with dots like `<Foo.Bar>` to refer to components nested under object properties. This is useful when importing multiple components from a single file: import * as Form from './form-components' allows <Form.Input><Form.Label>label</Form.Label></Form.Input>

Built-in components do not need registration

Built-in components can be used directly in templates without needing to be registered. They are tree-shakeable: they are only included in the build when they are used.

Importing built-in components in render functions

When using built-in components in render functions, they need to be imported explicitly. For example: import { h, Transition } from 'vue' and then h(Transition, { /* props */ }).

Transition component for single element animations

The <Transition> component provides animated transition effects to a single element or component. It wraps one child element and applies CSS transition classes to animate its entry and exit.

Transition props: name, css, type, duration, mode, appear, and custom classes

Transition component accepts props: name (string, generates CSS class names like .fade-enter), css (boolean, default true, applies CSS transition classes), type ('transition' | 'animation', specifies which events to wait for), duration (number | { enter: number; leave: number }, explicit durations), mode ('in-out' | 'out-in' | 'default', timing sequence of leaving/entering, default is simultaneous), appear (boolean, default false, applies transition on initial render), enterFromClass, enterActiveClass, enterToClass, appearFromClass, appearActiveClass, appearToClass, leaveFromClass, leaveActiveClass, leaveToClass (all strings for custom transition class names).

Transition events

Transition emits events: @before-enter, @before-leave, @enter, @leave, @appear, @after-enter, @after-leave, @after-appear, @enter-cancelled, @leave-cancelled (v-show only), @appear-cancelled.

Transition example with v-if

<Transition> <div v-if="ok">toggled content</div> </Transition>

Transition example with dynamic key

<Transition> <div :key="text">{{ text }}</div> </Transition>

Transition example with dynamic component

<Transition name="fade" mode="out-in" appear> <component :is="view"></component> </Transition>

Transition example listening to events

<Transition @after-enter="onTransitionComplete"> <div v-show="ok">toggled content</div> </Transition>

TransitionGroup for animating multiple elements

The <TransitionGroup> component provides transition effects for multiple elements or components in a list. It renders as a fragment by default but can render a wrapper DOM element via the tag prop.

TransitionGroup props

TransitionGroup accepts the same props as Transition except mode, plus: tag (string, if not defined renders as fragment), moveClass (string, customizes CSS class applied during move transitions, use kebab-case in templates).

TransitionGroup requires unique keys

Every child in a <transition-group> must be uniquely keyed for the animations to work properly.

TransitionGroup move transitions with FLIP technique

TransitionGroup supports moving transitions via CSS transform. When a child's position on screen has changed after an update, it gets applied a moving CSS class (auto generated from the name attribute or configured with the move-class prop). If the CSS transform property is transition-able when the moving class is applied, the element will be smoothly animated to its destination using the FLIP technique.

Give your agent this brain