Moonlit Torii

Getting Started with Vue 3

Templates, component communication, Composition API, routing, and state management.

My Vue 3 notes on templates, components, reactivity, routing, and state management.

Example setup: Supply a Vue 3 global build for HTML examples that reference vue.js, the appropriate files and dependencies for single-file components, and your own backend for sample endpoints.

MVC and MVVM architecture

MVVM is a useful model for Vue, but Vue is a progressive UI framework. Form synchronization does not change the props-down, events-up component data flow.

Original figure 001: MVC and MVVM architecture

Basic syntax

The data option

data() returns state for each instance. Vue 3 proxies should not be conflated with Vue 2's Object.defineProperty implementation.

Reactive data interception: Vue 3 primarily uses proxies to track object property access and mutation.

Original figure 002: The data option

Original figure 003: The data option

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <h2>{{message}}</h2>
    <button @click=changeMessage>changeMessage</button>
  </div>


  <script src="./vue.js"></script>

  <script>
    const app = Vue.createApp({
      // data: option api
      data() {
        return {
          message: "hello world"
        }
      },
      // methods: option api
      methods: {
        changeMessage: function() {
          this.message = "VUE"
        },
      },
    })
    app.mount("#app")
  </script>
</body>

</html>

The methods option

Use regular functions for methods that need the component's this.

Original figure 004: The methods option

Original figure 005: The methods option

Original figure 006: The methods option

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <h2>{{count}}</h2>
    <button @click="increase">+1</button>
    <button @click="decrease">-1</button>
  </div>


  <script src="./vue.js"></script>

  <script>
    const app = Vue.createApp({
      // data: option api
      data() {
        return {
          count: 0
        }
      },
      // methods: option api
      methods: {
        increase: function() {
          this.count++
        },
        decrease: function() {
          this.count--
        }
      },
    })
    app.mount("#app")
  </script>
</body>

</html>

Vue fundamentals

Template syntax

Original figure 007: Template syntax

Text interpolation syntax.

Original figure 008: Template syntax

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <!-- 基本使用 -->
    <h2>{{ message }}</h2>
    <h2>当前:{{ count }}</h2>
    <h2>{{ count * 2 }}</h2>
    <!-- 里面也可以写表达式 -->
     <!-- 甚至 三元运算符 -->
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          message: "hello vue",
          count: 0
        }
      },
    })
    app.mount("#app")
  </script>
</body>

</html>

v-once

Original figure 009: v-once

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <h2 v-once>{{ message }}</h2>
    <button @click="changeMes">changeMes</button>
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          message: "hello vue"
        }
      },
      methods: {
        changeMes: function() {
          this.message = "2333"
          console.log(this.message);
        }
      },
    })
    app.mount("#app")
  </script>
</body>

</html>

v-text

Original figure 010: v-text

v-html

Use trusted or properly sanitized HTML. Content is not compiled as a Vue template; do not trust arbitrary user input.

Original figure 011: v-html

v-pre

Original figure 012: v-pre

v-cloak

Pair it with [v-cloak] { display: none; }, mainly for in-DOM templates without a build step.

Original figure 013: v-cloak

v-memo for performance optimization (3.2+)

The v-memo dependency array controls subtree updates. This example lists only name, so changes to age or height alone may not appear; include all displayed dependencies when required.

Official v-memo reference

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app" v-memo="[name]">
    <h2>{{ name }}</h2>
    <h2>{{ age }}</h2>
    <h2>{{ height }}</h2>
    <button @click="updateInfo">改变信息</button>
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          name: "why",
          age: 213,
          height: 1.88
        }
      },
      methods: {
        updateInfo: function() {
          // 只有name改变才会重新渲染 优化性能 (超过1000个情况下)
          this.name = "kobe"
        }
      },
    })
    app.mount("#app")
  </script>
</body>

</html>

v-bind: attribute binding

Original figure 014: v-bind: attribute binding

Binding basic attributes

Original figure 015: Binding basic attributes

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>


</head>

<body>
  <div id="app">
    <!-- 切换图片功能 -->
    <button @click="changeIMG">changeIMG</button>
    <!-- 绑定img -->
    <!-- <img v-bind:src="imgURL" alt=""> -->
    <!-- 语法糖 -->
    <img :src="imgShow ? imgURL1 : imgURL2" alt="">
    <a :href="baiduURL">baidu</a>
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          imgShow: true,
          imgURL1: "https://images.unsplash.com/photo-1520209759809-a9bcb6cb3241?q=80&w=1170&auto=format&fit=crop&ixlib=rb-4.1.0&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D",
          imgURL2: "https://www.gokite.travel/wp-content/uploads/2025/02/2.-Experience-Thrills-Top-Rides-at-IMG-Adventure-Park-Dubai.webp",
          baiduURL: "https://www.baidu.com"
        }
      },
      methods: {
        changeIMG: function() {
          this.imgShow = !this.imgShow
        }
      },
    })
    app.mount("#app")
  </script>
</body>

</html>

Binding class

Original figure 016: Binding class

Original figure 017: Binding class

Original figure 018: Binding class

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

  <style>
    .active {
      color: red
    }

    .bgc {
      background-color: pink;
    }
  </style>
</head>

<body>
  <div id="app">
    <!-- 不同的状态下 有不同的class -->
    <!-- 动态绑定 可以写 对象语法 -->

    <!-- 对象语法的基本使用 -->
    <button :class="{active: isActive}" @click="btnClick">change</button>

    <!-- 动态绑定class 和 普通class 可以并列使用 -->

    <!-- 数组语法的基本使用 -->
    <h2 :class="['active', {bgc: isActive}]">hello world</h2>
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          isActive: false
        }
      },
      methods: {
        btnClick: function () {
          this.isActive = !this.isActive
        }
      },
    })
    app.mount("#app")
  </script>
</body>

</html>

Binding style

Original figure 019: Binding style

Original figure 020: Binding style

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <!-- 绑定style属性 -->
    <!-- 属性名要写成驼峰命名法 -->

    <!-- 对象写法 -->
    <h2 :style="{color: color, fontSize: '42px'}">{{ message }}</h2>

    <!-- 数组写法 -->
    <h2 :style="[objStyle, {backgroundColor: 'pink'}]">{{ message }}</h2>
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          message: "hello vue",
          color: "skyblue",
          objStyle: {
            color: this.color,
            fontSiz: "30px"
          }
        }
      },
    })
    app.mount("#app")
  </script>
</body>

</html>

Dynamic attribute arguments

Original figure 021: Dynamic attribute arguments

Binding an attribute object

Original figure 022: Binding an attribute object

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <!-- <h2 name="why" age="18" height="1.88">{{ message }}</h2> -->
    <!-- 或者一个个绑定 太麻烦 -->
    <!-- <h2 :name="name" :age="age" :height="height">{{ message }}</h2> -->

    <!-- v-bind绑定对象 -->
    <!-- 会自动遍历绑定 -->
    <h2 v-bind="infos"></h2>
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          message: "hello vue",
          infos: {
            name: "why",
            age: 18,
            height: 1.88
          },
          name: "why",
          age: 18,
          height: 1.88
        }
      },
    })
    app.mount("#app")
  </script>
</body>

</html>

Event binding

v-on

Original figure 023: v-on

Original figure 024: v-on

Basic v-on usage

Original figure 025: Basic v-on usage

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

  <style>
    .box {
      width: 100px;
      height: 100px;
      background-color: orange;
    }
  </style>
</head>

<body>
  <div id="app">
    <!-- 基本写法 -->
    <!-- <div class="box" v-on:click="divClick"></div> -->
    <!-- 语法糖写法 -->
    <div class="box" @click="divClick"></div>


    <!-- 绑定方法的位置 也可以写成一个表达式 (不常用) -->
    <!-- 不建议在模板中写js -->
    <h2>{{ count }}</h2>
    <button @click="count++">+1</button>
    <button @click="count--">-1</button>

    <!-- 绑定其他方法 -->
    <div class="box" @mousemove="divMouseMove"></div>

    <!-- 多个元素的事件绑定 -->
    <div class="box" @click="divClick" @mousemove="divMouseMove"></div>
    <!-- <div class="box" v-on="{click: divClick, mousemove: divMouseMove}"></div> -->
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          count: 0
        }
      },
      methods: {
        divClick() {
          console.log("2333");
        },
        divMouseMove() {
          console.log(1231231231);
        },
      },
    })
    app.mount("#app")
  </script>
</body>

</html>

Passing event arguments

Original figure 026: Passing event arguments

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <button @click="btn1Click">button1</button>
    <button @click="btn2Click('why', 18)">button2</button>
    <!-- 想要获取event对象 $event -->
    <button @click="btn3Click('jack', 23, $event)">button3</button>
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {

        }
      },
      methods: {
        // 1.默认参数 event对象
        // 绑定的时候没有传递任何的参数 event事件会默认传递进来
        btn1Click(event) {
          console.log(event);
        },
        // 2.明确参数
        btn2Click(name, age) {
          console.log(name, age);
        },
        btn3Click(name, age, event) {
          console.log(name, age, event);
        },
      },
    })
    app.mount("#app")
  </script>
</body>

</html>

Event modifiers

.stop stops propagation and .prevent prevents default behavior. Order matters; do not combine .passive with .prevent.

Original figure 027: Event modifiers

markdown
stopPropagation stops event propagation.
Event modifiers invoke common event operations declaratively.

Conditional rendering

Original figure 028: Conditional rendering

v-if

Original figure 029: v-if

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <ul v-if="names.length !== 0">
      <li v-for="item in names">{{ item }}</li>
    </ul>

    <h2 v-else>当前没有数据,请获取数据再试!</h2>
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          names: ["abc", "cba", "nba"],
          // names: [],
        }
      },
      methods: {

      },
    })
    app.mount("#app")
  </script>
</body>

</html>

In a Vue template, use template with directives such as v-if to group multiple nodes.

A div creates a real DOM wrapper.

That template group does not add a wrapper; this is not a general description of every HTML template element.

Here it provides logical grouping.

Original figure 030: v-if

v-show

Original figure 031: v-show

Differences between v-if and v-show

v-if creates or destroys a subtree; v-show toggles display and does not support template.

Original figure 032: Differences between v-if and v-show

v-for

Original figure 033: v-for

Basic v-for usage

Vue template v-for syntax accepts either in or of as its separator.

This equivalence concerns template syntax only; JavaScript for...in and for...of are different.

Original figure 034: Basic v-for usage

Original figure 035: Basic v-for usage

Original figure 036: Basic v-for usage

Detecting array updates

Original figure 037: Detecting array updates

Reactive arrays still support ordinary JavaScript array methods.

For non-mutating methods such as filter and map, assign the result to reactive state. Whether watch runs depends on its source and options.

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <ul>
      <li v-for="item in names">{{ item }}</li>
    </ul>
    <button @click="changeList">change</button>
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          names: ["abc", "csa", "ojp"]
        }
      },
      methods: {
        changeList() {
          // this.names = ["why", "jack"]

          // 通过一些方法修改数组中的元素
          this.names.push("why")

					// 不修改原数组的方法是不能监听的 watch
        }
      },
    })
    app.mount("#app")
  </script>
</body>

</html>

The role of key in v-for

Use stable, unique keys. Avoid array indexes for reordered or stateful lists; put a template v-for key on the template.

Original figure 038: The role of key in v-for

html
 <!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <ul>
      <!-- key要求是唯一标识 id -->
      <li v-for="item in letters" :key="item">{{ item }}</li>
    </ul>
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          letters: [123, 123, 123, 3424235, 5463]
        }
      },
      methods: {

      },
    })
    app.mount("#app")
  </script>
</body>

</html>

VNode

A VNode is a JavaScript object that describes a node.

Original figure 039: VNode

Original figure 040: VNode

Original figure 041: VNode

Original figure 042: VNode

Original figure 043: VNode

Original figure 044: VNode

Original figure 045: VNode

Original figure 046: VNode

Original figure 047: VNode

Original figure 048: VNode

Options API

Original figure 049: Options API

Computed properties

Computed values are cached by reactive dependencies. Keep getters free of side effects; methods run on each call and can take arguments.

Original figure 050: Computed properties

Original figure 051: Computed properties

Original figure 052: Computed properties

Original figure 053: Computed properties

Original figure 054: Computed properties

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <!-- 直接拼接 不太好 -->
    <!-- 直接写名称 不用写() -->
    <h2>{{ fullName }}</h2>
    <!-- 显示分数等级 -->
    <h2>{{ scoreLevel }}</h2>
    <!-- 反转单词文本 -->
    <h2>{{ reverseText }}</h2>
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          firstName: "kobe",
          lastName: "Beyant",
          score: 80,
          text: "my name is why"
        }
      },
      methods: {

      },
      computed: {
        fullName() {
          return `${this.firstName} ${this.lastName}`
        },
        scoreLevel() {
          return this.score >= 60 ? '及格' : '不及格'
        },
        reverseText() {
          return this.text.split(" ").reverse().join(" ")
        },
      }
    })
    app.mount("#app")
  </script>
</body>

</html>

computed vs methods

markdown
Computed properties cache results across repeated reads.
No recalculation is needed until a reactive dependency changes.
Read the property without call parentheses; caching does not make every use faster than a method.

Original figure 055: computed vs methods

Original figure 056: computed vs methods

Computed getters and setters

The getter and setter define separate reading and writing rules; the empty setter in this example does not update the name.

Original figure 057: Computed getters and setters

Original figure 058: Computed getters and setters

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <!-- 直接拼接 不太好 -->
    <!-- 直接写名称 不用写() -->
    <h2>{{ fullName }}</h2>
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          firstName: "kobe",
          lastName: "Beyant",
        }
      },
      methods: {

      },
      computed: {
        fullName: {
          get() {
            return `${this.firstName} ${this.lastName}`
          },
          set() {

          }
        },
      }
    })
    app.mount("#app")
  </script>
</body>

</html>

The watch option

Object spread is a shallow copy, not a deep snapshot. toRaw returns the original object; mutating it should not drive reactive updates.

Original figure 059: The watch option

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <h2>{{ message }}</h2>
    <h2>{{ info }}</h2>
    <button @click="changeMessage">修改</button>
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          message: "hello vue",
          info: { name: "why", age: 18 }
        }
      },
      methods: {
        changeMessage() {
          this.message = "hello world"
          this.info = {name: "kobe"}
        }
      },
      watch: {
        message(newVal, oldVal) {
          console.log("message发生了改变", newVal, oldVal);
        },
        // 如果是对象类型 返回的是proxy
        info(newVal, oldVal) {
          console.log("info发生了变化", newVal, oldVal);
          // 获取原始对象 (直接解构)
          console.log({...newVal}, {...oldVal});
          // 获取原始对象 (Vue.toRaw())
          console.log(Vue.toRaw(newVal), Vue.toRaw(oldVal));
        },
      }
    })
    app.mount("#app")
  </script>
</body>

</html>

Original figure 060: The watch option

Watcher configuration

Nested changes may leave old and new values referencing the same object. immediate runs the callback immediately; use flush: post or nextTick for updated DOM.

Original figure 061: Watcher configuration

Original figure 062: Watcher configuration

Original figure 063: Watcher configuration

Original figure 064: Watcher configuration

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <h2>{{ info.name }}</h2>
    <button @click="changeInfo">修改</button>
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          info: { name: "why", age: 18 }
        }
      },
      methods: {
        changeInfo() {
          // 只是在改变属性
          this.info.name = "kobe"
        }
      },
      watch: {
        // 默认 没有开启 深度监听 deep
        info: {
          handler(newVal, oldVal) {
            console.log("修改了info", newVal, oldVal)
            console.log(newVal === oldVal);
          },
          // 进行深度监听
          deep: true,
          // 第一次渲染的时候 执行渲染器
          immediate: true,
        },
        "info.name": function(newVal, oldVal) {
          console.log(newVal, oldVal);
        },
      },
    })
    app.mount("#app")
  </script>
</body>

</html>

Complete example

Bind a unique list identifier with :key and keep cart quantities at zero or above.

Original figure 065: Complete example

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    table {
      border-collapse: collapse;
      text-align: center;
      background-color: whitesmoke;
    }

    th,
    td {
      border: 2px solid gray;
      padding: 8px 16px;
    }

    .active {
      background-color: skyblue;
    }
  </style>
</head>

<body>
  <div id="app">
    <template v-if="books.length === 0">
      <h2>购物车为空,请添加书籍!</h2>
    </template>

    <template v-else>
      <table>
        <thead>
          <tr>
            <th>序号</th>
            <th>书籍名称</th>
            <th>出版日期</th>
            <th>价格</th>
            <th>购买数量</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="(item, index) in books" :key="item.id" :class="{active: index === curIndex}">
            <td @click="clickIndex(index)">{{ index + 1 }}</td>
            <td @click="clickIndex(index)">{{ item.name }}</td>
            <td @click="clickIndex(index)">{{ item.date }}</td>
            <td @click="clickIndex(index)">{{ formatPrice(item.price) }}</td>
            <td>
              <button :disabled="item.count === 0" @click="decrement(index),clickIndex(index)">-</button>
              {{ item.count }}
              <button @click="increment(index),clickIndex(index)">+</button>
            </td>
            <td>
              <button @click="removeItem(index)">移除</button>
            </td>
          </tr>
        </tbody>
      </table>

      <h2>总价:{{ formatPrice(totalPrice) }}</h2>
    </template>

  </div>


  <script src="../vue.js"></script>

  <script src="./data.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          books: books,
          curIndex: -1,
        }
      },
      methods: {
        formatPrice(price) {
          return `¥${price}`
        },
        clickIndex(index) {
          this.curIndex = index
        },
        increment(index) {
          this.books[index].count++
        },
        decrement(index) {
          if (this.books[index].count > 0) this.books[index].count--
        },
        removeItem(index) {
          this.books.splice(index, 1)
          this.curIndex = -1
        }
      },
      computed: {
        totalPrice() {
          let total = 0
          this.books.forEach(element => total += element.price * element.count);
          return total
        },
      }
    })
    app.mount("#app")
  </script>
</body>

</html>
javascript
const books = [
  {
    id: 1,
    name: '《算法导论》',
    date: '2006-9',
    price: 85.00,
    count: 1
  },
  {
    id: 2,
    name: '《UNIX编程艺术》',
    date: '2006-2',
    price: 59.00,
    count: 1
  },
  {
    id: 3,
    name: '《编程珠玑》',
    date: '2008-10',
    price: 39.00,
    count: 1
  },
  {
    id: 4,
    name: '《代码大全》',
    date: '2006-3',
    price: 128.00,
    count: 1
  },
  {
    id: 5,
    name: '《你不知道JavaScript》',
    date: '2014-8',
    price: 88.00,
    count: 1
  },
]

Forms with v-model

Basic v-model usage

Original figure 066: Basic v-model usage

Original figure 067: Basic v-model usage

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <label for="account">
      <input type="text" v-model="account">
    </label>
    <label for="password">
      <input type="password" v-model="password">
    </label>
    <!-- <input type=" text" :value="message" @input="inputChange"> -->
      <!-- 等价于上面的效果 -->
      <!-- 双向绑定 -->
      <input type="text" v-model="message">
      <h2>{{ account }}</h2>
      <h2>{{ password }}</h2>
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          message: "hello vue",
          account: "",
          password: "",
        }
      },
      methods: {
        // inputChange(event) {
        //   this.message = event.target.value
        // }
      },
    })
    app.mount("#app")
  </script>
</body>

</html>

Original figure 068: Basic v-model usage

v-model with textarea

Original figure 069: v-model with textarea

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <textarea cols="30" rows="10" v-model="message"></textarea>

    <h2>{{ message }}</h2>
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          message: "hello vue"
        }
      },
      methods: {

      },
    })
    app.mount("#app")
  </script>
</body>

</html>

v-model with checkboxes

Original figure 070: v-model with checkboxes

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <label for="agree">
      <!-- 单选框 绑定过去的值 是Boolean -->
      <input id="agree" type="checkbox" v-model="isAgree" >同意协议
    </label>

    <h2>{{ isAgree }}</h2>
    <hr>

    <!-- 多选框 -->
    <!-- 注意:多选框要明确绑定一个value值 -->
    <!-- 绑定到一个数组中 选中会把value添加到数组中  -->
    <div class="hobbies">
      <label for="basketball">
        <input type="checkbox" id="basketball" v-model="hobbies" value="basketball">basketball
      </label>
      <label for="sing">
        <input type="checkbox" id="sing" v-model="hobbies" value="sing">sing
      </label>
      <label for="jump">
        <input type="checkbox" id="jump" v-model="hobbies" value="jump">jump
      </label>
      <label for="rap">
        <input type="checkbox" id="rap" v-model="hobbies" value="rap">rap
      </label>
    </div>

    <h2>{{ hobbies }}</h2>
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          isAgree: false,
          hobbies: [],
        }
      },
      methods: {

      },
    })
    app.mount("#app")
  </script>
</body>

</html>

v-model with radio buttons

Original figure 071: v-model with radio buttons

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <!-- 通过设置name让不同的radio互斥  -->
  <!-- 因为绑定同一个v-model 同样可以起到互斥的效果 -->
  <!-- 通过设置value 传输数据 -->
  <div id="app">
    <div class="gender">
      <label for="male">
        <input type="radio" v-model="gender" value="male">male
      </label>
      <label for="female">
        <input type="radio" v-model="gender" value="female">female
      </label>
    </div>

    <h2>{{ gender }}</h2>
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          // 默认选中直接写
          gender: "male"
        }
      },
      methods: {

      },
    })
    app.mount("#app")
  </script>
</body>

</html>

v-model with select

Original figure 072: v-model with select

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <!-- select单选 -->
    <select v-model="message">
      <option value="apple">apple</option>
      <option value="orange">orange</option>
      <option value="banana">banana</option>
    </select>

    <h2>{{ message }}</h2>
    <hr>

    <!-- select多选 -->
    <select multiple size="2" v-model="fruits">
      <option value="apple">apple</option>
      <option value="orange">orange</option>
      <option value="banana">banana</option>
    </select>

    <h2>{{ fruits }}</h2>
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          message: "",
          fruits: []
        }
      },
      methods: {

      },
    })
    app.mount("#app")
  </script>
</body>

</html>

Binding option values

Original figure 073: Binding option values

markdown
Values can come dynamically from the server rather than being hard-coded.

Use v-for together with v-bind.

v-model modifiers

.lazy uses change, .trim removes outer whitespace, and .number attempts conversion. Empty input may still be a string; validation is still required.

Original figure 074: v-model modifiers

Original figure 075: v-model modifiers

Original figure 076: v-model modifiers

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <!-- lazy:绑定change事件 -->
    <!-- change事件 失去焦点/提交 才会变更 -->
    <input type="text" v-model.lazy="message">
    <h2>{{ message }}</h2>

    <!-- number:自动将内容转化为数字 -->
    <input type="text" v-model.number="count">
    <!-- 只能输入数字 没必要用number -->
    <input type="number" v-model="count">
    <h2>{{ count }}-{{ typeof count }}</h2>

    <!-- trim:去除首尾的空格 -->
    <!-- 多个空格连起来 浏览器会渲染成一个空格 -->
    <input type="text" v-model.trim="content">
    <h2>{{ content }}</h2>

    <!-- 多个修饰符连用的话 就多个.加在后面 -->
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      data() {
        return {
          message: "hello vue",
          count: 0,
          content: "",
        }
      },
      methods: {

      },
    })
    app.mount("#app")
  </script>
</body>

</html>

Original figure 077: v-model modifiers

Component fundamentals and scaffolding

Basic concepts

Original figure 078: Basic concepts

Original figure 079: Basic concepts

Original figure 080: Basic concepts

Original figure 081: Basic concepts

Component registration

Original figure 082: Component registration

Registering global components

Original figure 083: Registering global components

Original figure 084: Registering global components

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <!-- 使用product-item -->
    <product-item></product-item>
    <product-item></product-item>
    <product-item></product-item>
  </div>


  <script src="../vue.js"></script>

  <script>
    // 组件App根组件
    const App = {}

    // 开发一个productItem组件
    const productItem = {
      template: `<h1>我是一个组件</h1>`
    }

    // 创建app
    const app = Vue.createApp(App)

    // 注册全局组件
    // 组件名称 - 对象
    app.component("product-item", productItem)

    // 挂载app
    app.mount("#app")
  </script>
</body>

</html>

Component names

Original figure 085: Component names

Registering local components

Original figure 086: Registering local components

Original figure 087: Registering local components

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <div id="app">
    <product-item></product-item>
    <product-item></product-item>
    <product-item></product-item>
  </div>


  <script src="../vue.js"></script>

  <script>
    const app = Vue.createApp({
      components: {
        "product-item": {
          template: `<h1>我是一个组件</h1>`
        }
      },
      data() {
        return {
        }
      },
      methods: {

      },
    })
    app.mount("#app")
  </script>
</body>

</html>

Ways of developing with Vue

Original figure 088: Ways of developing with Vue

Original figure 089: Ways of developing with Vue

Original figure 090: Ways of developing with Vue

Original figure 091: Ways of developing with Vue

Original figure 092: Ways of developing with Vue

Using Vue CLI

Vue CLI is in maintenance mode. Use create-vue with Vite for new projects.

markdown
npm i -g @vue/cli
vue create my-project

vue create my-project --packageManager pnpm

npm -g update

Original figure 093: Using Vue CLI

Original figure 094: Using Vue CLI

Original figure 095: Using Vue CLI

Original figure 096: Using Vue CLI

Communication between components

Nested components

Original figure 097: Nested components

Original figure 098: Nested components

Component communication

Original figure 099: Component communication

Original figure 100: Component communication

Parent-to-child props: array and object syntax

Object and array defaults normally need factories. Props are shallow readonly; keep mutations explicit.

vue
<template>
  <div class="infos">
    <h2>{{ name }}</h2>
    <h2>{{ age }}</h2>
    <h2>{{ height }}</h2>
  </div>
</template>

<script>
  export default {
    // props 数组 (父传子)
    // 数组语法的弊端:
    // 1.不能对类型进行验证
    // 2.没有默认值的
    // props: ["name", "age", "height"]

    // props 对象 (父传子)
    // 对象语法(必须)
    // 如果类型type 是Object对象类型 包括array
    // 需要用函数返回 () => ({ name: "jack" })
    props: {
      name: {
        type: String,
        default: "默认值"
      },
      age: Number,
      height: Number
    }
  }
</script>

Original figure 101: Parent-to-child props: array and object syntax

Original figure 102: Parent-to-child props: array and object syntax

Original figure 103: Parent-to-child props: array and object syntax

Original figure 104: Parent-to-child props: array and object syntax

Original figure 105: Parent-to-child props: array and object syntax

Original figure 106: Parent-to-child props: array and object syntax

Fallthrough attributes

Undeclared attributes and listeners are in $attrs. Single-root components normally forward them; multiple roots need an explicit destination.

Original figure 107: Fallthrough attributes

Original figure 108: Fallthrough attributes

Child-to-parent events with emit

vue
<template>
  <div class="app">
    <h2>当前计数: {{ counter }}</h2>

    <AddCounter @add="btnAdd"></AddCounter>
    <SubCounter @sub="btnSub"></SubCounter>
  </div>
</template>

<script>
  import AddCounter from './components/AddCounter.vue';
  import SubCounter from './components/SubCounter.vue';

  export default {
    components: {
      AddCounter,
      SubCounter,
    },
    data() {
      return {
        counter: 0
      }
    },
    methods: {
      btnAdd(count) {
        this.counter += count
      },
      btnSub(count) {
        this.counter -= count
      }
    }
  }
</script>

<style scoped></style>
vue
<template>
  <div class="add">
    <button @click="btnClick(1)">+1</button>
    <button @click="btnClick(5)">+5</button>
    <button @click="btnClick(10)">+10</button>
  </div>
</template>

<script>
  export default {
		emits: ["add"],
    methods: {
      btnClick(count) {
        // 让子组件发送一个自定义事件
        // 第一个是事件名称 后面是参数
        this.$emit("add", count)
      }
    }
  }
</script>

<style scoped>

</style>

Original figure 109: Child-to-parent events with emit

Original figure 110: Child-to-parent events with emit

Validating custom event arguments

A failed emits validator warns in development but does not stop emission. Reject invalid operations before emit; component events do not bubble.

Original figure 111: Validating custom event arguments

Original figure 112: Validating custom event arguments

Slots and communication beyond parent-child relationships

Original figure 113: Slots and communication beyond parent-child relationships

Basic slot usage

vue
<template>
  <div class="app">
    <ShowMessage title="哈哈哈">
      <button>我是按钮</button>
    </ShowMessage>
    <ShowMessage title="哈哈哈">
      <p>我是内容</p>
    </ShowMessage>
    <ShowMessage title="233"></ShowMessage>
  </div>
</template>

<script>
  import ShowMessage from './components/ShowMessage.vue';

  export default {
    components: {
      ShowMessage,
    },
  }
</script>

<style scoped></style>
vue
<template>
  <h2>{{ title }}</h2>
  <div class="content">
    <slot>
      <p>我是默认值</p>
    </slot>
  </div>
</template>

<script>
  export default {
    props: {
      title: {
        type: String,
        default: "",
      },
    },
    data() {
      return {

      }
    },
  }
</script>

<style scoped></style>

Original figure 114: Basic slot usage

Original figure 115: Basic slot usage

Original figure 116: Basic slot usage

Original figure 117: Basic slot usage

Named slots

vue
<template>
  <div class="app">
    <NavBar>
      <template v-slot:left>
        <button>返回</button>
      </template>
      <template v-slot:center>
        <a href="#">登录</a>
      </template>
      <template v-slot:right>
        <div>现在</div>
      </template>

      <template v-slot:default>
        <p>233</p>
      </template>
    </NavBar>
  </div>
</template>

<script>
  import NavBar from './components/NavBar.vue';

  export default {
    components: {
      NavBar,
    },
  }
</script>

<style scoped></style>
vue
<template>
  <div class="nav-bar">
    <div class="left">
      <slot name="left">left</slot>
    </div>
    <div class="center">
      <slot name="center">right</slot>
    </div>
    <div class="right">
      <slot name="right">right</slot>
    </div>
  </div>

  <div class="other">
    <slot></slot>
  </div>
</template>

<script>
  export default {

  }
</script>

<style scoped>
  .nav-bar {
    display: flex;
    height: 44px;
    line-height: 44px;
    text-align: center;
  }

  .left {
    width: 80px;
    background-color: skyblue;
  }

  .center {
    flex: 1;
    background-color: orange;
  }

  .right {
    width: 80px;
    background-color: aquamarine;
  }
</style>

Original figure 118: Named slots

Dynamic slot names

vue
<template>
  <div class="app">
    <NavBar>
      <template v-slot:left>
        <button>返回</button>
      </template>
      <template v-slot:center>
        <a href="#">登录</a>
      </template>
      <template v-slot:right>
        <div>现在</div>
      </template>

      <template v-slot:default>
        <p>233</p>
      </template>
    </NavBar>

    <!-- nav-bar只给一个插槽传入数据 -->
    <!-- 动态插槽名 -->
    <NavBar>
      <template v-slot:[position]>
        <a href="#">注册</a>
      </template>
    </NavBar>
    <button @click="position = 'left'">左边</button>
    <button @click="position = 'center'">中间</button>
    <button @click="position = 'right'">右边</button>
  </div>
</template>

<script>
  import NavBar from './components/NavBar.vue';

  export default {
    components: {
      NavBar,
    },
    data() {
      return {
        position: 'left',
      }
    },
  }
</script>

<style scoped></style>

Original figure 119: Dynamic slot names

The named slot shorthand #header

Original figure 120: The named slot shorthand #

Render scope

Parent-authored slot content uses parent scope; expose child data explicitly through slot props.

Original figure 121: Render scope

Original figure 122: Render scope

Scoped slots

vue
<template>
  <div class="app">
    <TabControl :titles="['衣服', '裤子', '鞋子']" @tab-item-click="tabItemClick">
      <template #default="data">
        <button>{{ data.item }}</button>
      </template>
    </TabControl>

    <h1>{{ pageContent[curIndex] }}</h1>
  </div>
</template>

<script>
  import TabControl from './components/TabControl.vue';

  export default {
    components: {
      TabControl,
    },
    data() {
      return {
        curIndex: 0,
        pageContent: ["衣服页面", "裤子页面", "鞋子页面"],
      }
    },
    methods: {
      tabItemClick(index) {
        this.curIndex = index
      }
    },
  }
</script>

<style scoped></style>
vue
<template>
  <div class="tab-control">
    <template v-for="(item, index) in titles" :key="index">
      <div class="tab-control-item"
          :class="{ active: curIndex === index }"
          @click="clickIndex(index)">
        <slot :item="item">
          {{ item }}
        </slot>
      </div>
    </template>
  </div>
</template>

<script>
  export default {
    emits: ["tabItemClick"],
    props: {
      titles: {
        type: Array,
        default: () => []
      }
    },
    data() {
      return {
        curIndex: 0,
      }
    },
    methods: {
      clickIndex(index) {
        this.curIndex = index
        this.$emit("tabItemClick", this.curIndex)
      }
    }
  }
</script>

Original figure 123: Scoped slots

Original figure 124: Scoped slots

Original figure 125: Scoped slots

Original figure 126: Scoped slots

Communication beyond parent-child relationships

provide/inject passes subtree dependencies, while Pinia manages shared business state. They can coexist.

Original figure 127: Communication beyond parent-child relationships (original state-management note)

Global event buses

Vue 3 removed instance $on, $off, and $once. External event buses require explicit subscription cleanup.

Original figure 128: Global event buses

Original figure 129: Global event buses

Original figure 130: Global event buses

provide and inject: dependency injection

Provide a ref or computed to preserve reactivity; passing a plain current value does not synchronize future changes. A computed getter must return its result.

Original figure 131: provide and inject: dependency injection

Original figure 132: provide and inject: dependency injection

Original figure 133: provide and inject: dependency injection

vue
<template>
  <div class="app">
    <Home></Home>
  </div>
</template>

<script>
  import { computed } from 'vue';
  import Home from './components/Home.vue';

  export default {
    components: {
      Home,
    },
    // provide: {
    //   name: "why",
    //   age: 18
    // },
    data() {
      return {
        message: "hello world"
      }
    },
    // 这种写法 才能绑定this
    // 这样message 才会更新 不是简单的赋值
    provide() {
      return {
        name: "why",
        age: 18,
        message: computed(() => {
          return this.message
        })
      }
    }
  }
</script>

<style scoped></style>
vue
<template>
  <div class="home-banner">
    <h2>{{ name }}</h2>
    <h2>{{ age }}</h2>
  </div>
</template>

<script>
  export default {
    inject: ["name", "age"]
  }
</script>

<style scoped></style>

Original figure 134: provide and inject: dependency injection

Additional component topics

Lifecycle hooks

Register hooks synchronously in setup. Access template DOM after mounting and clean up listeners, timers, and pending requests on unmount.

Original figure 135: Lifecycle hooks

Original figure 136: Lifecycle hooks

Original figure 137: Lifecycle hooks

Original figure 138: Lifecycle hooks

markdown
mounted: access the DOM after mounting.
unmounted: release resources and remove event listeners.

Component $refs and DOM access

Refs may be null before mounting or after v-if removes an element. Await nextTick for updated DOM; script setup components expose intended methods with defineExpose.

vue
<template>
  <div class="app">
    <h2 ref="title">{{ message }}</h2>
    <button ref="btn" @click="changeTitle">change</button>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        message: "hello world",
      }
    },
    methods: {
      changeTitle() {
        // this.message = "你好啊"

        // 获取h2/btn元素
        console.log(this.$refs.title);
        console.log(this.$refs.btn);
      }
    }
  }
</script>

Original figure 139: Component $refs and DOM access

Original figure 140: Component $refs and DOM access

Dynamic components

vue
<template>
  <div class="app">
    <div class="tabs">
      <template v-for="(item, index) in tabs" :key="item">
        <button :class="{ active: curIndex === index }"
                @click="curIndex = index">
          {{ item }}
        </button>
      </template>
    </div>

    <div class="views">
      <!-- 方法1: 通过v-if实现 -->
      <!-- 方法2: 动态组件 -->
      <component :is="tabs[curIndex]"></component>
    </div>
  </div>
</template>

<script>
  import About from "./views/About.vue";
  import Category from "./views/Category.vue";
  import Home from "./views/Home.vue";

  export default {
    components: {
      Home,
      About,
      Category,
    },
    data() {
      return {
        tabs: ["home", "about", "category"],
        curIndex: 0,
      };
    },
  };
</script>

<style scoped>
  .active {
    color: red;
  }
</style>

Original figure 141: Dynamic components

Original figure 142: Dynamic components

Original figure 143: Dynamic components

Original figure 144: Dynamic components

KeepAlive

include/exclude match component names and max limits the cache. Cached components are deactivated, not immediately unmounted; manage resources on activation and deactivation.

vue
<!-- 状态会丢失 例如计数器等等 -->
<template>
  <div class="app">
    <div class="tabs">
      <template v-for="(item, index) in tabs" :key="item">
        <button :class="{ active: curIndex === index }" @click="curIndex = index">
          {{ item }}
        </button>
      </template>
    </div>

    <div class="views">
      <!-- 方法1: 通过v-if实现 -->
      <!-- 方法2: 动态组件 -->
      <!-- include 来自于name属性 -->
      <keep-alive include="Home">
        <component :is="tabs[curIndex]"></component>
      </keep-alive>
    </div>
  </div>
</template>

<script>
  import About from "./views/About.vue";
  import Category from "./views/Category.vue";
  import Home from "./views/Home.vue";

  export default {
    components: {
      Home,
      About,
      Category,
    },
    data() {
      return {
        tabs: ["home", "about", "category"],
        curIndex: 0,
      };
    },
  };
</script>

<style scoped>
  .active {
    color: red;
  }
</style>
vue
<template>
  <div class="home">
    <h2>home组件</h2>
    <h2>{{ counter }}</h2>
    <button @click="counter++">+1</button>
  </div>
</template>

<script>
  export default {
    name: "Home",
    data() {
      return {
        counter: 0
      }
    }
  }
</script>

<style scoped></style>

Original figure 145: KeepAlive

Original figure 146: KeepAlive

Original figure 147: KeepAlive

Code splitting with webpack

Original figure 148: Code splitting with webpack

Async components in Vue

defineAsyncComponent wraps async components and dynamic import enables splitting. Lazy routes use component: () => import(...) directly.

vue
<template>
  <div class="app">
    <div class="tabs">
      <template v-for="(item, index) in tabs" :key="item">
        <button :class="{ active: curIndex === index }" @click="curIndex = index">
          {{ item }}
        </button>
      </template>
    </div>

    <div class="views">
      <!-- 方法1: 通过v-if实现 -->
      <!-- 方法2: 动态组件 -->
      <!-- include 来自于name属性 -->
      <keep-alive include="Home">
        <component :is="tabs[curIndex]"></component>
      </keep-alive>
    </div>
  </div>
</template>

<script>
  import { defineAsyncComponent } from "vue";

  import Home from "./views/Home.vue";
  import About from "./views/About.vue";
  // import Category from "./views/Category.vue";
  const AsyncCategory = defineAsyncComponent(() => import("./views/Category.vue"))

  export default {
    components: {
      Home,
      About,
      Category: AsyncCategory,
    },
    data() {
      return {
        tabs: ["home", "about", "category"],
        curIndex: 0,
      };
    },
  };
</script>

<style scoped>
  .active {
    color: red;
  }
</style>

Original figure 149: Async components in Vue

Original figure 150: Async components in Vue

Component v-model

The modelValue plus update:modelValue contract works in Vue 3. Vue 3.4+ offers defineModel as shorthand.

vue
<template>
  <div class="app">
    <!-- input v-model -->
    <input v-model="message">
    <input :value="message" @input="message = $event.target.value">

    <!-- 组件v-model -->
    <Counter v-model="appCounter"></Counter>
    <Counter :modelValue="appCounter" @update:modelValue="appCounter = $event"></Counter>
  </div>
</template>

<script>
  import Counter from './Counter.vue';

  export default {
    data() {
      return {
        message: "hello world",
        appCounter: 100,
      }
    },
    components: {
      Counter,
    },
  }
</script>

<style scoped></style>
vue
<template>
  <div class="counter">
    <h2>counter: {{ modelValue }}</h2>
    <button @click="changeCounter">修改数据</button>
  </div>
</template>

<script>
  export default {
    props: {
      modelValue: {
        type: Number,
        default: 0,
      }
    },
    emits: ["update:modelValue"],
    methods: {
      changeCounter() {
        this.$emit("update:modelValue", 99)
      }
    }
  }
</script>

<style scoped></style>

Original figure 151: Component v-model

Original figure 152: Component v-model

Original figure 153: Component v-model

Mixins

Options API still supports mixins. Composables make dependencies and returned values explicit and reduce naming collisions.

vue
<template>
  <div class="home">
    <h2>home组件</h2>
  </div>
</template>

<script>
  import messageMixin from './mixins/message-mixin';

  export default {
    mixins: [messageMixin]
  }
</script>

<style scoped></style>
javascript
export default {
  data() {
    return {
      message: "hello world",
    };
  },
};

Original figure 154: Mixins

Original figure 155: Mixins

Original figure 156: Mixins

Original figure 157: Mixins

Composition API

Original figure 158: Composition API

Original figure 159: Composition API

Original figure 160: Composition API

The setup function

setup does not use component this. Regular setup returns template bindings; script setup requires Vue 3.2+ and exposes top-level bindings automatically.

Original figure 161: The setup function

Updating state

Original figure 162: Updating state

vue
<template>
  <div class="app">
    <h2>{{ title }}</h2>
    <h2>{{ message }}</h2>
    <button @click="changeMessage">change</button>
  </div>
</template>

<script setup>
  import { reactive, ref } from 'vue';

  // 定义简单数据类型 (ref也可以定义复杂数据类型)
  let title = ref("hello world")

  // 定义复杂数据类型
  let message = reactive({
    username: "coderwhy",
    password: "2133245",
  })

  function changeMessage() {
    message.username = "hahahaha"
  }
</script>

<style lang="scss" scoped></style>

reactive: object state

reactive supports objects, arrays, Maps, and Sets, not primitives. Use a ref for whole-value replacement and keep proxy references stable.

Original figure 163: reactive: object state

ref: primitive and object values

Refs hold primitives, objects, or arrays. JavaScript uses .value; top-level template refs are usually unwrapped.

Original figure 164: ref: primitive and object values

Original figure 165: ref: primitive and object values

One-way data flow in Vue

Props follow one-way data flow and are shallow readonly; nested mutation should not obscure state ownership.

markdown
Data flows from parent to child through props.
Children should not reassign their props.
Request changes through emitted events and let the parent update its own state.
This keeps ownership clear and makes updates easier to trace.

Using readonly

readonly creates a readonly view, while the original owner can still update writable state; it does not freeze the data source.

Original figure 166: Using readonly

Original figure 167: Using readonly

Original figure 168: Using readonly

Inspecting reactive values

Original figure 169: Inspecting reactive values

toRefs and toRef

Ordinary destructuring disconnects primitive properties; toRef/toRefs retain the link. toFixed returns a string; convert it with Number when a numeric result is needed.

vue
<template>
  <div class="app">
    <h2>{{ name }} - {{ age }}-{{ height }}</h2>
    <button @click="increase">+1</button>
    <button @click="decrease">-0.1</button>
  </div>
</template>

<script setup>
  import { reactive, toRef, toRefs } from 'vue';

  const info = reactive({
    name: "why",
    age: 18,
    height: 1.99
  })

  // 被解构后为了防止失去响应式
  const { name, age } = toRefs(info)
  const height = toRef(info, "height")

  function increase() {
    info.age++
  }

  function decrease() {
    info.height -= 0.1
    info.height = Number(info.height.toFixed(2))
  }
</script>

<style lang="scss" scoped></style>

Original figure 170: toRefs and toRef

Original figure 171: toRefs and toRef

Original figure 172: toRefs and toRef

Original figure 173: toRefs and toRef

Other utilities

Original figure 174: Other utilities

Original figure 175: Other utilities

computed

vue
<template>
  <div class="app">
    <h2>{{ fullName }}</h2>
    <h2>{{ fullName }}</h2>
    <h2>{{ fullName }}</h2>
    <button @click="setFullname">changeFullname</button>
  </div>
</template>

<script setup>
  import { computed, reactive } from 'vue';

  const names = reactive({
    firstName: "kobe",
    lastName: "black",
  })

  // const fullName = computed(() => {
  //   return names.firstName + " " + names.lastName
  // })
  const fullName = computed({
    get: function() {
      return names.firstName + " " + names.lastName
    },
    set: function(newVal) {
      const tempName = newVal.split(" ")
      names.firstName = tempName[0]
      names.lastName = tempName[1]
    }
  })

  function setFullname() {
    fullName.value = "coder why"
  }
</script>

<style lang="scss" scoped></style>

Original figure 176: computed

Template refs in setup

vue
<template>
  <div class="app">
    <h2 ref="titleRef">hello world</h2>
    <button @click="getElement">getElement</button>
  </div>
</template>

<script setup>
  import { onMounted, ref } from 'vue';

  const titleRef = ref()

  // mounted生命周期函数
  onMounted(() => {
    console.log(titleRef.value);
  })

  function getElement() {
    console.log(titleRef.value);
  }
</script>

<style lang="scss" scoped></style>

Original figure 177: Template refs in setup

Lifecycle hooks

onBeforeUnmount runs before a component unmounts. Vue 3.5+ also provides useTemplateRef for template refs.

markdown
onBeforeMount
onMounted
onBeforeUpdate
onUpdated
onBeforeUnmount
....

Original figure 178: Lifecycle hooks

Original figure 179: Lifecycle hooks

Original figure 180: Lifecycle hooks

provide and inject: dependency injection

Dependency injection is useful for themes and form context and can work alongside Pinia.

Original figure 181: provide and inject (original state-management note)

Original figure 182: provide and inject (original state-management note)

watch and watchEffect

watch has explicit sources; watchEffect runs immediately and tracks synchronous reads before the first await. Do not call stopWatch during its first synchronous run before initialization. Requests also need cleanup.

vue
<template>
  <div class="app">
    <h2>{{ counter }}</h2>
    <button @click="counter++">+1</button>

    <button @click="message = '2333'">修改message</button>
    <button @click="info.age = 22">修改info</button>
  </div>
</template>

<script setup>
  import { reactive, ref, watch, watchEffect } from 'vue';

  let counter = ref(0)

  let message = ref("hello world")
  let info = reactive({
    name: "jack",
    age: 18
  })

  // 监听数据变量
  watch(message, (newVal, oldVal) => {
    console.log(newVal, oldVal);
  })
  watch(info, (newVal, oldVal) => {
    console.log(newVal, oldVal);
  }, {
    immediate: true
  })

  // 监听数据变化后,获取普通数据对象
  // 原来是proxy 结构成一个普通对象
  // 侦听多个源 放到一个数组中
  watch(() => ({ ...info }), (newVal, oldVal) => {
    console.log(newVal, oldVal);
  })

  // 监听counter的变化
  // 可以用watch
  // 1.watchEffect传入的函数默认会直接被执行
  // 2.在执行的过程之中,会自动收集依赖(依赖响应式的数据)
  const stopWatch = watchEffect(() => {
    console.log("-----", counter.value, message.value);
    if (counter.value >= 10) {
      stopWatch()
    }
  })


</script>

<style lang="scss" scoped></style>

Original figure 183: watch and watchEffect

Original figure 184: watch and watchEffect

Original figure 185: watch and watchEffect

Original figure 186: watch and watchEffect

Original figure 187: watch and watchEffect

Original figure 188: watch and watchEffect

Composable practice

Original figure 189: Composable practice

Original figure 190: Composable practice

Original figure 191: Composable practice

script setup syntax

defineProps, defineEmits, and defineExpose are compiler macros and need no import. Use defineExpose to expose methods such as infoBtnClick. Vue 3.5+ reactive props destructuring differs from ordinary reactive destructuring.

Original figure 192: script setup syntax

Original figure 193: script setup syntax

Original figure 194: script setup syntax

javascript
// 定义props
const props = defineProps({
  name: {
    type: String,
    default: "",
  }
})

const emits = defineEmits(["infoBtnClick"])
function infoBtnClick() {}


defineExpose({
  foo: infoBtnClick,
})

Original figure 195: script setup syntax

Original figure 196: script setup syntax

Original figure 197: script setup syntax

Original figure 198: script setup syntax

Original figure 199: script setup syntax

Original figure 200: script setup syntax

Original figure 201: script setup syntax

Original figure 202: script setup syntax

Original figure 203: script setup syntax

Original figure 204: script setup syntax

Original figure 205: script setup syntax

Original figure 206: script setup syntax

Original figure 207: script setup syntax

Original figure 208: script setup syntax

Original figure 209: script setup syntax

Original figure 210: script setup syntax

Original figure 211: script setup syntax

Vue Router

The evolution of frontend routing

Original figure 212: The evolution of frontend routing

Original figure 213: The evolution of frontend routing

Original figure 214: The evolution of frontend routing

Original figure 215: The evolution of frontend routing

Original figure 216: The evolution of frontend routing

Introducing Vue Router

Register the router and create referenced views. Vue Router 4 supports Vue 3.

vue
<template>
  <div class="app">
    <h2>app</h2>
    <div class="nav">
      <!-- 写active-class会重命名 router-link-active  -->
      <router-link to="/home">首页</router-link>
      <router-link to="/about">关于</router-link>
      <router-link to="/user/123">用户123</router-link>
      <router-link to="/user/321">用户321</router-link>
      <router-link to="/order">订单</router-link>

      <button @click="logoutClick">推出登录</button>
    </div>
    <router-view></router-view>
  </div>
</template>

<script setup>
  function logoutClick() {
    localStorage.removeItem("token")
  }
</script>

<style scoped>
  .router-link-active {
    color: skyblue;
    font-size: 20px;
  }
</style>
javascript
import { createApp } from 'vue'

import App from './App.vue'
import router from './router'

const app = createApp(App)
app.use(router)
app.mount('#app')
javascript
import { createRouter } from "vue-router";
import { createWebHashHistory } from "vue-router";
import { createWebHistory } from "vue-router";

// import Home from "../views/Home.vue";
// import About from "../views/About.vue";
// 分包操作 (路由的懒加载)
// const Home = () => import("../views/Home.vue")
// const About = () => import("../views/About.vue")

// 创建一个路由:映射关系
const router = createRouter({
  // history: createWebHashHistory(),
  history: createWebHistory(),
  routes: [
    // 进入页面的时候 直接到home
    {
      path: "/",
      redirect: "/home",
    },
    {
      // 可以增加name属性 独一无二的
      name: "home",
      path: "/home",
      component: () => import("../views/Home.vue"),
      // 可以往 meta里面加东西
      // meta: {},
      // 路由的嵌套 children
      children: [
        {
          path: "",
          redirect: "/home/recommend",
        },
        {
          // path 变为了子路径
          path: "recommend",
          component: () => import("../views/HomeRecommend.vue"),
        },
        {
          path: "ranking",
          component: () => import("../views/HomeRanking.vue"),
        },
      ],
    },
    {
      path: "/about",
      component: () => import("../views/About.vue"),
    },
    {
      name: "user",
      // 后面不是写死的 后面可能跟上id (动态路由)
      path: "/user/:id",
      component: () => import("../views/User.vue"),
    },
    {
      name: "NotFound",
      // 表示匹配不到具体的路径
      // path: "/:pathMatch(.*)*", 会放到一个数组中
      path: "/:pathMatch(.*)",
      component: () => import("../views/NotFound.vue"),
    },
    {
      name: "order",
      path: "/order",
      component: () => import("../views/Order.vue")
    },
    {
      name: "login",
      path: "/login",
      component: () => import("../views/Login.vue")
    }
  ],
});

// 动态路由
let isAdmin = true
if (isAdmin) {
  // 一级路由
  router.addRoute({
    path: "/admin",
    component: () => import("../views/Admin.vue")
  })
  // 添加二级路由
  router.addRoute("home", {
    path: "songs",
    component: () => import("../views/HomeSongs.vue")
  })
}

// 获取所有路由记录的数组
// console.log(router.getRoutes());


// 路由导航守卫 guard
// 进行任何路由跳转之前 传入的beforeEach中的函数都会被回调
// (有点像watch 拦截的意思)
router.beforeEach((to, from) => {
  const token = localStorage.getItem("token")
  if (to.path === "/order" && !token) {
    return "/login"
  }
  // 进入到任何别的页面时 判断用户是否登录
  // if (to.path !== "/login") {
  //   return "/login"
  // }
})

export default router;
vue
<template>
  <div class="home">
    <h2>home组件</h2>
    <div class="nav">
      <router-link to="/home/recommend">推荐</router-link>
      <router-link to="/home/ranking">排行</router-link>
    </div>
    <router-view></router-view>

    <!-- 编程式路由的跳转 -->
    <button @click="aboutBtnClick">跳转到about</button>
  </div>
</template>

<script setup>
  import { useRouter } from 'vue-router';

  const router = useRouter()

  function aboutBtnClick() {
    // router.push("/about")
    router.push({
      path: "/about",
      // 可以传参
      query: {
        userName: "why",
        age: 18,
      }
    })
  }
</script>

<style lang="scss" scoped></style>

Original figure 217: Introducing Vue Router

Original figure 218: Introducing Vue Router

Original figure 219: Introducing Vue Router

Default routes

A default nested child uses an empty path. HTML5 history deployment requires a server fallback for application routes.

Original figure 220: Default routes

Original figure 221: Default routes

Original figure 222: RouterLink properties

Lazy route loading

Original figure 223: Lazy route loading

Original figure 224: Lazy route loading

Other route properties

Original figure 225: Other route properties

Dynamic route matching

Parameter changes may reuse a component. Watch the relevant route.params or use an update guard rather than assuming remounting.

Original figure 226: Dynamic route matching

Original figure 227: Dynamic route matching

Original figure 228: Dynamic route matching

Original figure 229: Dynamic route matching

Nested routes

Original figure 230: Nested routes

Original figure 231: Nested routes

Programmatic navigation

Use named routes with params; params are not automatically incorporated when path is supplied. push adds history; replace replaces it.

Original figure 232: Programmatic navigation

Original figure 233: Programmatic navigation

Original figure 234: Programmatic navigation

Moving through browser history

Original figure 235: Moving through browser history

Managing routes dynamically

Original figure 236: Managing routes dynamically

Removing dynamic routes

Original figure 237: Removing dynamic routes

Route navigation guards.

Original figure 238: Removing dynamic routes

Original figure 239: Removing dynamic routes

The order is leave guards, beforeEach, update guards, beforeEnter, async components, beforeRouteEnter, beforeResolve, confirmation, afterEach, and DOM updates. Client token checks do not replace backend authorization.

Original figure 240: Navigation guard resolution order

State management with Vuex

Vuex 4 supports Vue 3; new applications can use Pinia. Mutations are synchronous; actions handle async work.

Original figure 241: State management with Vuex

Original figure 242: State management with Vuex

Original figure 243: State management with Vuex

Original figure 244: State management with Vuex

Installing Vuex

Original figure 245: Installing Vuex

Creating a store

This store uses modules.home without namespaced, so mutation/getter names remain global. /api/example needs a backend implementation.

vue
<template>
  <div class="app">
    <h2>{{ $store.state.home.counter }}</h2>
    <Home></Home>
    <button @click="increment()">+1</button>
  </div>
</template>

<script setup>
  import { useStore } from "vuex";
  import Home from "./views/Home.vue"



  // 想要修改数据 必须用mutations
  const store = useStore()

  // function increment() {
  //   store.commit("increment")
  // }
  // 不用像上面那样写了 用useStore + commit替代
  const increment = () => store.commit("increment")

  // function increment() {
  //   store.dispatch(increment)
  // }

</script>

<style lang="scss" scoped></style>
javascript
import { createStore } from "vuex"

import homeModules from "./modules/home"

const store = createStore({
  state: () => ({

  }),
  // 对state的数据进行处理
  getters: {

  },
  mutations: {

  },
  actions: {

  },
  modules: {
    home: homeModules,
  }
})

export default store
javascript
export default {
  state: () => ({
    counter: 100,
    name: "coderwhy",
    level: 25,
  }),
  mutations: {
    increment(state) {
      state.counter++;
    },
  },
  getters: {
    doubleCounter(state) {
      return state.counter * 2;
    },
  },
  actions: {
    async incrementAction(context) {
      // context.commit 用于提交mutation
      // getters state

      const res = await fetch("/api/example");
      const data = await res.json();
      context.commit("increment");
    },
  },
};

vue
<template>
  <div class="home">
    <h2>{{ $store.state.home.counter }}</h2>
    <h2>{{ name }}</h2>
    <h2>{{ level }}</h2>
    <h2>{{ doubleCounter }}</h2>
  </div>
</template>

<script setup>
  import { computed } from 'vue';
  import { useStore } from 'vuex';

  // mapState针对options API可以 (借助于this解构)
  // 官方推荐用store.state
  const store = useStore()

  const name = computed(() => store.state.home.name)
  const level = computed(() => store.state.home.level)
  const doubleCounter = computed(() => store.getters.doubleCounter)
</script>

<style lang="scss" scoped></style>
javascript
import { createApp } from 'vue'
import App from './App.vue'
import store from './store'

createApp(App).use(store).mount('#app')

Original figure 246: Creating a store

Original figure 247: Creating a store

A single state tree

Original figure 248: A single state tree

Original figure 249: A single state tree

Mapping state with mapState

vue
<template>
  <div class="home">
    <h2>{{ $store.state.counter }}</h2>
    <h2>{{ name }}</h2>
    <h2>{{ level }}</h2>
  </div>
</template>

<script setup>
  import { computed } from 'vue';
  import { useStore } from 'vuex';

  // mapState针对options API可以 (借助于this解构)
  // 官方推荐用store.state
  const store = useStore()

  const name = computed(() => store.state.name)
  const level = computed(() => store.state.level)
</script>

<style lang="scss" scoped></style>

Original figure 250: Basic getter usage

Basic getter usage

Getters derive and return values from state; avoid mutating state inside them.

Read getters through store.getters, including the module prefix for namespaced modules.

Original figure 251: Basic getter usage

Original figure 252: Basic getter usage

Original figure 253: Basic getter usage

The mapGetters helper

Original figure 254: The mapGetters helper

Basic mutation usage

Original figure 255: Basic mutation usage

Original figure 256: Basic mutation usage

Mutation type constants

Original figure 257: Mutation type constants

The mapMutations helper

Original figure 258: The mapMutations helper

Original figure 259: The mapMutations helper

Basic action usage

Original figure 260: Basic action usage

Original figure 261: Basic action usage

Original figure 262: Basic action usage

Async actions

Original figure 263: Async actions

Store modules

Original figure 264: Store modules

Original figure 265: Store modules

Namespaced modules

With namespaced: true, commit, dispatch, and getters need module prefixes; mapping helpers can take a module name.

Original figure 266: Namespaced modules

Original figure 267: Namespaced modules

State management with Pinia

Original figure 268: State management with Pinia

Original figure 269: State management with Pinia

Original figure 270: State management with Pinia

Stores

javascript
import { createApp } from "vue";
import App from "./App.vue";
import pinia from "./stores";

createApp(App).use(pinia).mount("#app");
javascript
import { createPinia } from "pinia";

const pinia = createPinia();

export default pinia
javascript
import { defineStore } from "pinia";

const useUser = defineStore("user", {
  state: () => ({
    name: "why",
    age: 22,
    level: 100,
  }),
  actions: {
    increment() {
      this.age++
    },
    async fetchData() {
      const res = await fetch("xxx")
      const data = res.json()
      return data
    }
  }
});

export default useUser;

javascript
// 定义一个关于counter的store
import { defineStore } from "pinia";

const useCounter = defineStore("counter", {
  state: () => ({
    count: 99,
  }),
  getters: {
    doubleCount(state) {
      return state.count * 2
    },
    doubleCountAddone(state) {
      return this.doubleCount + 1
    }
  },
})

export default useCounter
vue
<template>
  <div class="home">
    <h2>home page</h2>
    <h2>{{ count }}</h2>
    <h2>{{ doubleCount }}</h2>
    <h2>{{ doubleCountAddone }}</h2>
    <hr>
    <h2>{{ name }} {{ age }} {{ level }}</h2>
    <button @click="changeUser">changeUser</button>
    <button @click="resetUser">reset user</button>
    <button @click="increment()">age + 1</button>
  </div>
</template>

<script setup>
  import useCounter from '@/stores/counter';
  import useUser from '@/stores/user';
  import { storeToRefs } from 'pinia';

  const counterStore = useCounter()
  const userStore = useUser()

  const {
    count,
    doubleCount,
    doubleCountAddone
  } = storeToRefs(counterStore)
  const {
    name,
    age,
    level,
  } = storeToRefs(userStore)

  function increment() {
    userStore.increment()
  }

  function fetchData() {
    userStore.fetchData().then(res => {
      console.log(res);
    })
  }

  function changeUser() {
    // 一个个修改 (正常就这样用)
    userStore.name = "Jack"
    userStore.age = 25
    userStore.level = 200

    // 一次性修改多个数据
    // userStore.$patch({
    //   name: "james",
    //   age: 34,
    // })

    // 替换state为一个新的对象
    // userStore.$state = {
    //   name: "curry",
    //   level: 200
    // }
  }

  function resetUser() {
    userStore.$reset()
  }
</script>

<style lang="scss" scoped></style>

Original figure 271: Stores

Original figure 272: Stores

Original figure 273: Stores

State

Original figure 274: State

Updating and resetting state

Pinia allows direct changes or $patch. Option Stores have $reset; Setup Stores implement it. Assigning $state applies a patch rather than replacing the reactive object.

Original figure 275: Updating and resetting state

Original figure 276: Updating and resetting state

Defining getters

Use storeToRefs for state and getters; actions can be destructured directly. TypeScript getters that use this need explicit return types.

Original figure 277: Defining getters

Original figure 278: Defining getters

Original figure 279: Defining getters

Defining actions

Original figure 280: Defining actions

Original figure 281: Defining actions

HTTP requests with Axios

Original figure 282: HTTP requests with Axios

Axios requests

javascript
import axios from "axios";

// 发送request请求
axios
  .request({
    url: "",
    method: "get",
  })
  .then((res) => {
    console.log(res.data);
  });

// 发送get请求
axios
  .get("", {
    params: {
      id: 56364543,
    },
  })
  .then((res) => {
    console.log(res.data);
  });

// 发送post请求
axios
  .post("", {
    username: "coderwhy",
    password: 213231,
  })
  .then((res) => {
    console.log(res.data);
  });

Original figure 283: Axios requests

Common configuration options

Use Promise.all for concurrency; one rejection does not cancel other requests. Pass an AbortController signal when cancellation is needed.

Original figure 284: Common configuration options

javascript
import axios from "axios";

// const baseURL = "http://xxxxxx"
// axios.defaults.baseURL = baseURL
// 接下来正常操作

// 还可以配置其他公共的配置
// axios.defaults.timeout = 10000

// axios发送多个请求
// 本质上就是promise all
axios.all([
  axios.get("xxx"),
  axios.get("xxx"),
]).then(res => {
  console.log(res);
})

Creating an Axios instance

javascript
import axios from "axios"

const instance = axios.create({
  baseURL: "http://xxx",
  timeout: 10000,
  headers: {},
})

instance.get()
instance.request()
instance.post()

Original figure 285: Creating an Axios instance

Request and response interceptors

Request and response interceptors return config and response respectively. Error callbacks return rejected promises so requests continue and errors propagate.

javascript
import axios from "axios"

// 对实例配置拦截器
// 前面是成功回调 后面是失败回调
axios.interceptors.request.use(
  (config) => config,
  (error) => Promise.reject(error)
)
axios.interceptors.response.use(
  (response) => response,
  (error) => Promise.reject(error)
)

Original figure 286: Request and response interceptors

Original figure 287: Request and response interceptors

Additional advanced Vue syntax

Teleport changes physical DOM placement; h and createVNode are not identical aliases, and Vue JSX needs its own transform.

Original figure 288: Additional advanced Vue syntax

Original figure 289: Additional advanced Vue syntax

Original figure 290: Additional advanced Vue syntax

Original figure 291: Additional advanced Vue syntax

Original figure 292: Additional advanced Vue syntax

Original figure 293: Additional advanced Vue syntax

Original figure 294: Additional advanced Vue syntax

Original figure 295: Additional advanced Vue syntax

Original figure 296: Additional advanced Vue syntax

Original figure 297: Additional advanced Vue syntax

Original figure 298: Additional advanced Vue syntax

Original figure 299: Additional advanced Vue syntax

Original figure 300: Additional advanced Vue syntax

Original figure 301: Additional advanced Vue syntax

Original figure 302: Additional advanced Vue syntax

Original figure 303: Additional advanced Vue syntax

Original figure 304: Additional advanced Vue syntax

Original figure 305: Additional advanced Vue syntax

Original figure 306: Additional advanced Vue syntax

Original figure 307: Additional advanced Vue syntax

Original figure 308: Additional advanced Vue syntax

Transitions and animation in Vue 3

Transition handles one element/component; TransitionGroup handles keyed lists and has no mode. JavaScript transitions with css: false must call done appropriately.

Original figure 309: Transitions and animation in Vue 3

Original figure 310: Transitions and animation in Vue 3

Original figure 311: Transitions and animation in Vue 3

Original figure 312: Transitions and animation in Vue 3

Original figure 313: Transitions and animation in Vue 3

Original figure 314: Transitions and animation in Vue 3

Original figure 315: Transitions and animation in Vue 3

Original figure 316: Transitions and animation in Vue 3

Original figure 317: Transitions and animation in Vue 3

Original figure 318: Transitions and animation in Vue 3

Original figure 319: Transitions and animation in Vue 3

Original figure 320: Transitions and animation in Vue 3

Original figure 321: Transitions and animation in Vue 3

Original figure 322: Transitions and animation in Vue 3

Reactivity in Vue 2 and Vue 3

Vue 2 mainly uses Object.defineProperty. Vue 3 reactive uses proxies, while refs track through .value accessors. Reactivity and virtual DOM updates are different layers.

Original figure 323: Reactivity in Vue 2 and Vue 3

Original figure 324: Reactivity in Vue 2 and Vue 3

Original figure 325: Reactivity in Vue 2 and Vue 3

Original figure 326: Reactivity in Vue 2 and Vue 3

Original figure 327: Reactivity in Vue 2 and Vue 3

Original figure 328: Reactivity in Vue 2 and Vue 3

Original figure 329: Reactivity in Vue 2 and Vue 3

Original figure 330: Reactivity in Vue 2 and Vue 3

Original figure 331: Reactivity in Vue 2 and Vue 3

Original figure 332: Reactivity in Vue 2 and Vue 3

Original figure 333: Reactivity in Vue 2 and Vue 3

Builds and automated deployment

Vite typically builds dist with npm run build; align the Vite and router bases for subpaths. Do not put secrets in client environment variables.

21: Builds and automated deployment — PDF