Vue 2 和 Vue 3 在模板语法上有一些细微的变化,Vue 3 更加简洁。
Vue 2 示例:
- <template>
- <button v-on:click="handleClick">Click me</button>
- <input v-bind:value="value" />
- </template>
Vue 3 示例:
- <template>
- <button @click="handleClick">Click me</button>
- <input :value="value" />
- </template>
Vue 3 引入了 Composition API,使得逻辑更加清晰和模块化。
Vue 2 示例:
- <template>
- <div>
- <p>{{ message }}</p>
- </div>
- </template>
-
- <script>
- export default {
- data() {
- return {
- message: 'Hello Vue 2!'
- }
- },
- methods: {
- updateMessage() {
- this.message = 'Updated message'
- }
- }
- }
- </script>
Vue 3 示例:
- <template>
- <div>
- <p>{{ message }}</p>
- </div>
- </template>
-
- <script setup>
- import { ref } from 'vue'
-
- const message = ref('Hello Vue 3!')
-
- const updateMessage = () => {
- message.value = 'Updated message'
- }
- </script>
Vue 3 在性能方面进行了大量优化,包括更快的渲染速度、更小的包体积等。
Vue 3 使用了新的渲染机制,减少了不必要的 DOM 操作,提升了渲染性能。
Vue 3 的编译器进行了优化,生成的代码更加高效。
Vue 3 引入了许多新特性,如 Teleport、Fragments、Suspense 等。
Teleport 组件允许将模态框或其他组件的内容渲染到 DOM 的其他位置,从而避免样式冲突。
Vue 3 示例:
- <template>
- <teleport to="body">
- <div class="modal" v-if="visible">
- <div class="modal-content">
- <span @click="closeModal" class="close">×</span>
- <p>{{ message }}</p>
- </div>
- </div>
- </teleport>
- </template>
-
- <script setup>
- import { ref } from 'vue'
-
- const visible = ref(true)
-
- const closeModal = () => {
- visible.value = false
- }
- </script>
Vue 3 支持 Fragments,允许在模板中使用多个根元素。
Vue 3 示例:
- <template>
- <div>First element</div>
- <div>Second element</div>
- </template>
Suspense 组件允许在异步组件加载时显示 fallback 内容。
Vue 3 示例:
- <template>
- <suspense>
- <template #default>
- <AsyncComponent />
- </template>
- <template #fallback>
- <div>Loading...</div>
- </template>
- </suspense>
- </template>
-
- <script setup>
- import { defineAsyncComponent } from 'vue'
-
- const AsyncComponent = defineAsyncComponent(() => import('./AsyncComponent.vue'))
- </script>
Composition API 是 Vue 3 的核心特性之一,它使得逻辑更加清晰和模块化。
示例:
- <template>
- <div>
- <p>{{ count }}</p>
- <button @click="increment">Increment</button>
- </div>
- </template>
-
- <script setup>
- import { ref } from 'vue'
-
- const count = ref(0)
-
- const increment = () => {
- count.value++
- }
- </script>
Teleport 组件允许将模态框或其他组件的内容渲染到 DOM 的其他位置,从而避免样式冲突。
示例:
- <template>
- <teleport to="body">
- <div class="modal" v-if="visible">
- <div class="modal-content">
- <span @click="closeModal" class="close">×</span>
- <p>{{ message }}</p>
- </div>
- </div>
- </teleport>
- </template>
-
- <script setup>
- import { ref } from 'vue'
-
- const visible = ref(true)
-
- const closeModal = () => {
- visible.value = false
- }
- </script>
Vue 3 中的计算属性和监听属性与 Vue 2 类似,但 Composition API 提供了更灵活的方式来使用它们。
计算属性示例:
- <template>
- <div>
- <p>First Name: <input v-model="firstName" /></p>
- <p>Last Name: <input v-model="lastName" /></p>
- <p>Full Name: {{ fullName }}</p>
- </div>
- </template>
-
- <script setup>
- import { ref, computed } from 'vue'
-
- const firstName = ref('')
- const lastName = ref('')
-
- const fullName = computed(() => {
- return `${firstName.value} ${lastName.value}`
- })
- </script>
监听属性示例:
- <template>
- <div>
- <p>Counter: {{ counter }}</p>
- <button @click="increment">Increment</button>
- </div>
- </template>
-
- <script setup>
- import { ref, watch } from 'vue'
-
- const counter = ref(0)
-
- const increment = () => {
- counter.value++
- }
-
- watch(counter, (newVal, oldVal) => {
- console.log(`Counter changed from ${oldVal} to ${newVal}`)
- })
- </script>
Vue 3 依然强调组件化开发,通过将页面拆分为多个独立的组件,提高代码的可维护性和复用性。
示例:
- <!-- MyComponent.vue -->
- <template>
- <div class="my-component">
- <h1>{{ title }}</h1>
- <p>{{ content }}</p>
- </div>
- </template>
-
- <script>
- export default {
- name: 'MyComponent',
- props: {
- title: String,
- content: String
- }
- }
- </script>
-
- <style scoped>
- .my-component {
- border: 1px solid #ccc;
- padding: 10px;
- margin: 10px;
- }
- </style>
Vue 3 提供了多种数据绑定方式,包括插值表达式、指令等。
示例:
- <template>
- <div id="app">
- <h1>{{ message }}</h1>
- <input v-model="message" />
- </div>
- </template>
-
- <script setup>
- import { ref } from 'vue'
-
- const message = ref('Hello Vue 3!')
- </script>
Vuex 是 Vue 的状态管理库,适用于大型应用的状态管理。
示例:
- // store.js
- import { createStore } from 'vuex'
-
- export default createStore({
- state: {
- count: 0
- },
- mutations: {
- increment(state) {
- state.count++
- }
- },
- actions: {
- increment({ commit }) {
- commit('increment')
- }
- },
- getters: {
- doubleCount(state) {
- return state.count * 2
- }
- }
- })
在组件中使用 Vuex:
- <template>
- <div>
- <p>Count: {{ count }}</p>
- <p>Double Count: {{ doubleCount }}</p>
- <button @click="increment">Increment</button>
- </div>
- </template>
-
- <script setup>
- import { computed } from 'vue'
- import { useStore } from 'vuex'
-
- const store = useStore()
-
- const count = computed(() => store.state.count)
- const doubleCount = computed(() => store.getters.doubleCount)
-
- const increment = () => {
- store.commit('increment')
- }
- </script>
Pinia 是 Vue 3 的新状态管理库,提供了更简洁的 API 和更好的 TypeScript 支持。
- // store.js
- import { defineStore } from 'pinia'
-
- export const useCounterStore = defineStore('counter', {
- state: () => ({
- count: 0
- }),
- actions: {
- increment() {
- this.count++
- }
- },
- getters: {
- doubleCount: (state) => state.count * 2
- }
- })
在组件中使用 Pinia:
- <template>
- <div>
- <p>Count: {{ count }}</p>
- <p>Double Count: {{ doubleCount }}</p>
- <button @click="increment">Increment</button>
- </div>
- </template>
-
- <script setup>
- import { useCounterStore } from './store'
- import { storeToRefs } from 'pinia'
-
- const counterStore = useCounterStore()
- const { count, doubleCount } = storeToRefs(counterStore)
- const { increment } = counterStore
- </script>
Vue 3 的路由管理依然使用 Vue Router,但需要安装 Vue Router 4。
安装 Vue Router:
- npm install vue-router@4
配置路由:
- // router.js
- import { createRouter, createWebHashHistory } from 'vue-router'
-
- const routes = [
- { path: '/', component: () => import('./views/Home.vue') },
- { path: '/about', component: () => import('./views/About.vue') }
- ]
-
- const router = createRouter({
- history: createWebHashHistory(),
- routes
- })
-
- export default router
在组件中使用路由:
- <template>
- <div>
- <router-link to="/">Home</router-link>
- <router-link to="/about">About</router-link>
- <router-view />
- </div>
- </template>
-
- <script setup>
- import { useRouter } from 'vue-router'
-
- const router = useRouter()
-
- const goToAbout = () => {
- router.push('/about')
- }
- </script>
Vue 3 的语法与 Vue 2 有一些变化,开发者需要熟悉新的语法,特别是 Composition API。
Vue 3 的生命周期钩子与 Vue 2 类似,但有一些变化,如 beforeDestroy 和 destroyed 被替换为 beforeUnmount 和 unmounted。
一些 Vue 2 的插件和库可能不兼容 Vue 3,开发者需要检查并更新这些依赖。
2020 年 9 月,Vue.js 发布了 3.0 版本,带来了许多新特性和性能优化。与此同时,Vue 2 在 2023 年底正式停止维护,这意味着开发者需要逐步过渡到 Vue 3。本文详细介绍 Vue 2 和 Vue 3 的核心区别、知识点、基础及应用,帮助开发者更好地理解和应用这些技术。