### Install Dependencies and Run Dev Server with Bun Source: https://cn.vuejs.org/guide/quick-start After creating a Vue project, navigate into the project directory, install dependencies using Bun, and start the development server. ```bash $ cd $ bun install $ bun run dev ``` -------------------------------- ### Install Dependencies and Run Dev Server with npm Source: https://cn.vuejs.org/guide/quick-start After creating a Vue project, navigate into the project directory, install dependencies using npm, and start the development server. ```bash $ cd $ npm install $ npm run dev ``` -------------------------------- ### Install Dependencies and Run Dev Server with pnpm Source: https://cn.vuejs.org/guide/quick-start After creating a Vue project, navigate into the project directory, install dependencies using pnpm, and start the development server. ```bash $ cd $ pnpm install $ pnpm run dev ``` -------------------------------- ### Install Dependencies and Run Dev Server with Yarn Source: https://cn.vuejs.org/guide/quick-start After creating a Vue project, navigate into the project directory, install dependencies using Yarn, and start the development server. ```bash $ cd $ yarn $ yarn dev ``` -------------------------------- ### 在 setup 函数中访问 attrs Source: https://cn.vuejs.org/guide/components/attrs 在非 script setup 的 setup 函数中通过上下文访问 attrs。 ```js export default { setup(props, ctx) { // 透传 attribute 被暴露为 ctx.attrs console.log(ctx.attrs) } } ``` -------------------------------- ### Basic Composition API Component with ``` -------------------------------- ### Component Logic with Composition API and ``` -------------------------------- ### Basic Vue 3 App Initialization (Composition API) Source: https://cn.vuejs.org/guide/introduction.html This example demonstrates creating a Vue application instance using the Composition API with the `setup` function. It uses `ref` to create a reactive 'count' state. ```js import { createApp, ref } from 'vue' createApp({ setup() { return { count: ref(0) } } }).mount('#app') ``` -------------------------------- ### Install a Vue.js Plugin Source: https://cn.vuejs.org/guide/reusability/plugins Demonstrates how to install a plugin using `app.use()`. Optional configuration options can be passed as a second argument. ```javascript import { createApp } from 'vue' const app = createApp({}) app.use(myPlugin, { /* 可选的选项 */ }) ``` -------------------------------- ### 使用 ``` -------------------------------- ### Vue.js App Initialization with Global Build (Composition API) Source: https://cn.vuejs.org/guide/quick-start Initialize a Vue application using the global build version with the Composition API and `
{{ message }}
``` -------------------------------- ### Counter Component using Single-File Component (Composition API with ``` -------------------------------- ### Reactive Props Destructuring with Defaults Source: https://cn.vuejs.org/guide/extras/reactivity-transform This example shows how to destructure props in ` ``` ```js export default { props: { msg: { type: String, required: true }, count: { type: Number, default: 1 }, foo: String }, setup(props) { watchEffect(() => { console.log(props.msg, props.count, props.foo) }) } } ``` -------------------------------- ### Using ` ``` -------------------------------- ### Vue.js App Initialization with ES Module Build (Composition API) Source: https://cn.vuejs.org/guide/quick-start Initialize a Vue application using the ES module build with the Composition API and ` ``` -------------------------------- ### 使用 components 选项进行局部注册 Source: https://cn.vuejs.org/guide/components/registration 在不使用 ``` ```javascript export default { components: { ComponentA: ComponentA } // ... } ``` -------------------------------- ### Plugin with install Method Source: https://cn.vuejs.org/guide/reusability/plugins Defines a plugin as an object with an `install` method. The `install` method receives the app instance and any additional options passed to `app.use()`. ```javascript const myPlugin = { install(app, options) { // 配置此应用 } } ``` -------------------------------- ### Emitting Events with `emit` from Setup Context Source: https://cn.vuejs.org/guide/essentials/component-basics Access the `emit` function from the setup context object in the `setup()` function to trigger custom events when not using ` ``` -------------------------------- ### 声明渲染函数 Source: https://cn.vuejs.org/guide/extras/render-function 在 setup() 或组件选项中声明渲染函数以替代模板。 ```javascript import { ref, h } from 'vue' export default { props: { /* ... */ }, setup(props) { const count = ref(1) // 返回渲染函数 return () => h('div', props.msg + count.value) } } ``` ```javascript export default { setup() { return () => 'hello world!' } } ``` ```javascript import { h } from 'vue' export default { setup() { // 使用数组返回多个根节点 return () => [ h('div'), h('div'), h('div') ] } } ``` ```javascript import { h } from 'vue' export default { data() { return { msg: 'hello' } }, render() { return h('div', this.msg) } } ``` ```javascript export default { render() { return 'hello world!' } } ``` ```javascript import { h } from 'vue' export default { render() { // 用数组来返回多个根节点 return [ h('div'), h('div'), h('div') ] } } ``` ```javascript function Hello() { return 'hello world!' } ``` -------------------------------- ### Provide Data in Options API Setup Function Source: https://cn.vuejs.org/guide/components/provide-inject When not using ` ``` -------------------------------- ### Provide Data with ``` -------------------------------- ### 渲染插槽 Source: https://cn.vuejs.org/guide/extras/render-function 展示如何在 setup 或 render 函数中访问并渲染插槽内容。 ```javascript export default { props: ['message'], setup(props, { slots }) { return () => [ // 默认插槽: //
h('div', slots.default()), // 具名插槽: //
h( 'div', slots.footer({ text: props.message }) ) ] } } ``` ```jsx // 默认插槽
{slots.default()}
// 具名插槽
{slots.footer({ text: props.message })}
``` ```javascript export default { props: ['message'], render() { return [ //
h('div', this.$slots.default()), //
h( 'div', this.$slots.footer({ text: this.message }) ) ] } } ``` ```jsx //
{this.$slots.default()}
//
{this.$slots.footer({ text: this.message })}
``` -------------------------------- ### Access Props in setup() (Options API) Source: https://cn.vuejs.org/guide/essentials/component-basics When not using ` ``` -------------------------------- ### Inject Data in Options API Setup Function Source: https://cn.vuejs.org/guide/components/provide-inject When not using ` ``` -------------------------------- ### Async setup() hook in Vue.js Source: https://cn.vuejs.org/guide/built-ins/suspense Use an asynchronous setup() hook to handle asynchronous operations within a component. This allows the component to fetch data or perform other async tasks before rendering. ```javascript export default { async setup() { const res = await fetch(...) const posts = await res.json() return { posts } } } ``` -------------------------------- ### Declaring Emitted Events with Script Setup Source: https://cn.vuejs.org/guide/essentials/component-basics Use the `defineEmits` macro within ` ``` -------------------------------- ### Create Vue App with npm Source: https://cn.vuejs.org/guide/quick-start Use npm to create a new Vue project with the official scaffolding tool. This command initiates the project setup process. ```bash $ npm create vue@latest ``` -------------------------------- ### Create Vue App with Bun Source: https://cn.vuejs.org/guide/quick-start Use Bun to create a new Vue project with the official scaffolding tool. This command initiates the project setup process. ```bash $ bun create vue@latest ``` -------------------------------- ### Exposing Properties from ` ``` -------------------------------- ### 局部注册异步组件 Source: https://cn.vuejs.org/guide/components/async 在组件选项或 script setup 中局部注册异步组件。 ```vue ``` ```vue ``` -------------------------------- ### Emitting Events with `emit` Function in Script Setup Source: https://cn.vuejs.org/guide/essentials/component-basics Use the `emit` function returned by `defineEmits` to trigger custom events from within the ` ``` -------------------------------- ### Expose Increment Function (Composition API) Source: https://cn.vuejs.org/guide/essentials/reactivity-fundamentals Declare functions within `setup()` to modify refs and return them along with the refs to be used in the template. ```javascript import { ref } from 'vue' export default { setup() { const count = ref(0) function increment() { // 在 JavaScript 中需要 .value count.value++ } // 不要忘记同时暴露 increment 函数 return { count, increment } } } ``` ```html ``` -------------------------------- ### Expose `ref` to Template (Composition API) Source: https://cn.vuejs.org/guide/essentials/reactivity-fundamentals Return refs from the `setup()` function to make them available in the component's template. Refs are automatically unwrapped in templates. ```javascript import { ref } from 'vue' export default { // `setup` 是一个特殊的钩子,专门用于组合式 API。 setup() { const count = ref(0) // 将 ref 暴露给模板 return { count } } } ``` ```html
{{ count }}
``` -------------------------------- ### Single-File Component with Composition API Source: https://cn.vuejs.org/guide/scaling-up/sfc An SFC utilizing the Composition API with ` ``` -------------------------------- ### Using composables in Options API Source: https://cn.vuejs.org/guide/reusability/composables Call composables within the `setup()` function of the Options API. Return the bindings from `setup()` to make them accessible via `this` and in the template. ```javascript import { useMouse } from './mouse.js' import { useFetch } from './fetch.js' export default { setup() { const { x, y } = useMouse() const { data, error } = useFetch('...') return { x, y, data, error } }, mounted() { // Properties exposed by setup() can be accessed via `this` console.log(this.x) } // ...other options } ``` -------------------------------- ### Create Vue App with pnpm Source: https://cn.vuejs.org/guide/quick-start Use pnpm to create a new Vue project with the official scaffolding tool. This command initiates the project setup process. ```bash $ pnpm create vue@latest ``` -------------------------------- ### Basic Single-File Component Structure Source: https://cn.vuejs.org/guide/scaling-up/sfc A standard SFC with template, script, and style blocks. This example uses the options API for component logic. ```vue ``` -------------------------------- ### Basic watch example Source: https://cn.vuejs.org/guide/essentials/watchers Use `watch` to react to changes in a specific reactive source. The callback is only triggered when the source value changes. ```js const todoId = ref(1) const data = ref(null) watch( todoId, async () => { const response = await fetch( `https://jsonplaceholder.typicode.com/todos/${todoId.value}` ) data.value = await response.json() }, { immediate: true } ) ``` -------------------------------- ### Define Component with ``` -------------------------------- ### Inject Data with ``` -------------------------------- ### Composition API: Basic Watcher Example Source: https://cn.vuejs.org/guide/essentials/watchers Use the `watch` function in the Composition API to trigger a callback when a reactive state changes. This example watches a ref named 'question' and performs an API call. ```vue ``` -------------------------------- ### Access Props in ``` -------------------------------- ### Boolean Prop Usage Examples Source: https://cn.vuejs.org/guide/components/props Demonstrates how Boolean props behave when passed without values. ```html ``` -------------------------------- ### Options API: Basic Watcher Example Source: https://cn.vuejs.org/guide/essentials/watchers Use the `watch` option in the Options API to trigger a function whenever a reactive property changes. This example watches the 'question' property and calls 'getAnswer' if it contains a question mark. ```javascript export default { data() { return { question: '', answer: 'Questions usually contain a question mark. ;-)', loading: false } }, watch: { // 每当 question 改变时,这个函数就会执行 question(newQuestion, oldQuestion) { if (newQuestion.includes('?')) { this.getAnswer() } } }, methods: { async getAnswer() { this.loading = true this.answer = 'Thinking...' try { const res = await fetch('https://yesno.wtf/api') this.answer = (await res.json()).answer } catch (error) { this.answer = 'Error! Could not reach the API. ' + error } finally { this.loading = false } } } } ``` ```html

Ask a yes/no question:

{{ answer }}

``` -------------------------------- ### Vue.js App Initialization with Global Build Source: https://cn.vuejs.org/guide/quick-start Initialize a Vue application using the global build version. All top-level APIs are available on the global `Vue` object. This example uses the Options API. ```html
{{ message }}
``` -------------------------------- ### Calling Store Method from Template Source: https://cn.vuejs.org/guide/scaling-up/state-management Example of calling the `store.increment()` method from a template's event handler. ```template ``` -------------------------------- ### Create Vue App with Yarn Source: https://cn.vuejs.org/guide/quick-start Use Yarn (v1+ or Modern) to create a new Vue project with the official scaffolding tool. This command initiates the project setup process. ```bash # For Yarn (v1+) $ yarn create vue # For Yarn Modern (v2+) $ yarn create vue@latest # For Yarn ^v4.11 $ yarn dlx create-vue@latest ``` -------------------------------- ### Initial HTML structure for modal Source: https://cn.vuejs.org/guide/built-ins/teleport Example of a nested modal structure that may face CSS layout issues. ```html

Tooltips with Vue 3 Teleport

``` -------------------------------- ### Provide Translation Dictionary Source: https://cn.vuejs.org/guide/reusability/plugins Installs the i18n plugin and passes a translation dictionary as an option. This dictionary is used by the `$translate` method. ```javascript import i18nPlugin from './plugins/i18n' app.use(i18nPlugin, { greetings: { hello: 'Bonjour!' } }) ``` -------------------------------- ### Component Logic with Options API Source: https://cn.vuejs.org/guide/introduction.html This example illustrates the Options API for defining a Vue component. It uses `data` for state, `methods` for actions, and `mounted` for lifecycle hooks, with all properties accessible via `this`. ```vue ``` -------------------------------- ### Template with Static and Dynamic Content Source: https://cn.vuejs.org/guide/extras/rendering-mechanism A template example showcasing static div elements ('foo', 'bar') that can be cached and a dynamic div with a {{ dynamic }} binding. The compiler can optimize the static parts. ```html
foo
bar
{{ dynamic }}
``` -------------------------------- ### Provide Options Object in Plugin Source: https://cn.vuejs.org/guide/reusability/plugins Uses `app.provide` within a plugin's install method to make the plugin's options accessible throughout the application via injection. ```javascript export default { install: (app, options) => { app.provide('i18n', options) } } ``` -------------------------------- ### Integrating SSR with Express Server Source: https://cn.vuejs.org/guide/scaling-up/ssr This example shows how to integrate Vue SSR into an Express.js server. It renders the Vue app and embeds the resulting HTML into a full HTML page response. Ensure `express` is installed. ```javascript import express from 'express' import { createSSRApp } from 'vue' import { renderToString } from 'vue/server-renderer' const server = express() server.get('/', (req, res) => { const app = createSSRApp({ data: () => ({ count: 1 }), template: `` }) renderToString(app).then((html) => { res.send(` Vue SSR Example
${html}
`) }) }) server.listen(3000, () => { console.log('ready') }) ``` -------------------------------- ### Automatic Watcher Stopping in ``` -------------------------------- ### Basic Vue 3 App Initialization (Options API) Source: https://cn.vuejs.org/guide/introduction.html This is a fundamental example showing how to create a Vue application instance and mount it to an HTML element using the Options API. It initializes a reactive 'count' data property. ```js import { createApp } from 'vue' createApp({ data() { return { count: 0 } } }).mount('#app') ``` -------------------------------- ### Declare Props with TypeScript Types in ``` -------------------------------- ### Reactive Destructuring of Props in ``` -------------------------------- ### Importing and Using a Single-File Component Source: https://cn.vuejs.org/guide/scaling-up/sfc Demonstrates how to import a Single-File Component as a standard ES module. Ensure your build tool is configured to handle `.vue` files. ```javascript import MyComponent from './MyComponent.vue' export default { components: { MyComponent } } ``` -------------------------------- ### Accessing Template Refs without useTemplateRef (Options API / Pre-3.5) Source: https://cn.vuejs.org/guide/essentials/template-refs Before `useTemplateRef`, declare a `ref` with the same name as the template's `ref` attribute. Access the element via `.value` after the component is mounted. If not using ` ``` ```js export default { setup() { const input = ref(null) // ... return { input } } } ``` ```vue ``` -------------------------------- ### Initialize Local State from Prop (Composition API) Source: https://cn.vuejs.org/guide/components/props Demonstrates how to use a prop as an initial value for a local reactive state (`ref`). The local state can then be mutated independently of the prop. ```javascript const props = defineProps(['initialCounter']) // 计数器只是将 props.initialCounter 作为初始值 // 像下面这样做就使 prop 和后续更新无关了 const counter = ref(props.initialCounter) ``` -------------------------------- ### Server Entry Point Using Shared App Logic Source: https://cn.vuejs.org/guide/scaling-up/ssr This server-side JavaScript file uses the shared `createApp` function to create a Vue application instance for rendering on the server. It's part of the Express server setup for SSR. ```javascript // (Irrelevant code omitted) import { createApp } from './app.js' server.get('/', (req, res) => { const app = createApp() renderToString(app).then(html => { // ... }) }) ``` -------------------------------- ### Use useFetch with a ref Source: https://cn.vuejs.org/guide/reusability/composables Pass a ref to `useFetch` to re-trigger fetches when the URL changes. The composable will automatically set up a listener. ```javascript const url = ref('/initial-url') const { data, error } = useFetch(url) // This will re-trigger the fetch url.value = '/new-url' ``` -------------------------------- ### Build Vue App for Production with Bun Source: https://cn.vuejs.org/guide/quick-start Generate a production-ready build of your Vue application using Bun. This command optimizes assets for deployment. ```bash $ bun run build ``` -------------------------------- ### 动态组件过渡 Source: https://cn.vuejs.org/guide/built-ins/transition 在动态组件切换时使用 Transition 组件,并配合 mode 属性控制过渡时序。 ```template ``` -------------------------------- ### Exporting Custom Element Constructors from a Library Source: https://cn.vuejs.org/guide/extras/web-components This example demonstrates creating an entry file for a Vue custom element library. It defines and exports individual custom element constructors and provides a `register` function for convenient global registration of all elements with their respective tag names. ```javascript import { defineCustomElement } from 'vue' import Foo from './MyFoo.ce.vue' import Bar from './MyBar.ce.vue' const MyFoo = defineCustomElement(Foo) const MyBar = defineCustomElement(Bar) // 分别导出元素 export { MyFoo, MyBar } export function register() { customElements.define('my-foo', MyFoo) customElements.define('my-bar', MyBar) } ``` -------------------------------- ### Typing Named Functional Components Source: https://cn.vuejs.org/guide/extras/render-function This example demonstrates how to type a named functional component in TypeScript, including props and events. ```tsx import type { SetupContext } from 'vue' type FComponentProps = { message: string } type Events = { sendMessage(message: string): void } function FComponent( props: FComponentProps, context: SetupContext ) { return ( ) } FComponent.props = { message: { type: String, required: true } } FComponent.emits = { sendMessage: (value: unknown) => typeof value === 'string' } ``` -------------------------------- ### Modifying Shared State Directly (Template) Source: https://cn.vuejs.org/guide/scaling-up/state-management Example of directly modifying the shared state `store.count` from a template using an event handler. ```template ``` -------------------------------- ### Build Vue App for Production with npm Source: https://cn.vuejs.org/guide/quick-start Generate a production-ready build of your Vue application using npm. This command optimizes assets for deployment. ```bash $ npm run build ``` -------------------------------- ### Create a Vue Application Instance Source: https://cn.vuejs.org/guide/essentials/application Use `createApp` to instantiate a new Vue application. This function takes root component options as an argument. ```javascript import { createApp } from 'vue' const app = createApp({ /* root component options */ }) ``` -------------------------------- ### Typing Anonymous Functional Components Source: https://cn.vuejs.org/guide/extras/render-function This example shows how to type an anonymous functional component using `FunctionalComponent` in TypeScript, including props and events. ```tsx import type { FunctionalComponent } from 'vue' type FComponentProps = { message: string } type Events = { sendMessage(message: string): void } const FComponent: FunctionalComponent = ( props, context ) => { return ( ) } FComponent.props = { message: { type: String, required: true } } FComponent.emits = { sendMessage: (value) => typeof value === 'string' } ``` -------------------------------- ### Render Filtered List in Template Source: https://cn.vuejs.org/guide/essentials/list Use `v-for` with a computed property to render a list of filtered items. This example shows rendering even numbers. ```html
  • {{ n }}
  • ``` -------------------------------- ### Register Global Component Source: https://cn.vuejs.org/guide/essentials/application Register a component globally using `app.component()` so it can be used anywhere within the application. This should be done before mounting. ```javascript app.component('TodoDeleteButton', TodoDeleteButton) ``` -------------------------------- ### Parent Component Data for Dynamic Props Source: https://cn.vuejs.org/guide/essentials/component-basics Example of parent component data structure (an array of posts) that can be used with `v-for` to pass dynamic props. ```js export default { // ... data() { return { posts: [ { id: 1, title: 'My journey with Vue' }, { id: 2, title: 'Blogging with Vue' }, { id: 3, title: 'Why Vue is so fun' } ] } } } ``` -------------------------------- ### 使用 v-for 渲染范围值 Source: https://cn.vuejs.org/guide/essentials/list `v-for` 可接受整数值,将模板重复多次,从 1 开始计数。 ```html {{ n }} ``` -------------------------------- ### 创建可复用的鼠标跟踪组合式函数 (useMouse) Source: https://cn.vuejs.org/guide/reusability/composables 将鼠标跟踪逻辑封装成一个名为 useMouse 的组合式函数。该函数管理 x 和 y 状态,并利用 onMounted 和 onUnmounted 钩子来添加和移除事件监听器。按照惯例,组合式函数名以 'use' 开头。 ```javascript import { ref, onMounted, onUnmounted } from 'vue' // 按照惯例,组合式函数名以“use”开头 export function useMouse() { // 被组合式函数封装和管理的状态 const x = ref(0) const y = ref(0) // 组合式函数可以随时更改其状态。 function update(event) { x.value = event.pageX y.value = event.pageY } // 一个组合式函数也可以挂靠在所属组件的生命周期上 // 来启动和卸载副作用 onMounted(() => window.addEventListener('mousemove', update)) onUnmounted(() => window.removeEventListener('mousemove', update)) // 通过返回值暴露所管理的状态 return { x, y } } ``` -------------------------------- ### Appear Transition Source: https://cn.vuejs.org/guide/built-ins/transition Apply a transition effect when a node is initially rendered. ```template ... ``` -------------------------------- ### Prop Naming Convention (CamelCase - Non-