BaiqiCMS网站管理系统

Nginx/IIS/Apache PHP5.3+ MySQL5.7+

外贸型/营销型/品牌企业网站建设首选CMS

Vue3 与 Vue2 的主要不同点及开发注意事项

一、核心不同点

1. 响应式系统

  • Vue2: 使用 Object.defineProperty,无法检测对象属性的添加/删除,需要 $set
  • Vue3: 使用 Proxy,可以检测属性的动态添加/删除,响应式更彻底

2. API 风格

  • Vue2: Options API(data、methods、computed 等分开)
  • Vue3: 同时支持 Options API 和 Composition API(setup 语法糖)

3. 生命周期钩子

Vue2 Vue3 (Composition API)
beforeCreate setup()
created setup()
beforeMount onBeforeMount
mounted onMounted
beforeUpdate onBeforeUpdate
updated onUpdated
beforeDestroy onBeforeUnmount
destroyed onUnmounted

4. 全局 API 变化

// Vue2
Vue.component('my-component', {...})
Vue.directive('my-directive', {...})

// Vue3
app.component('my-component', {...})
app.directive('my-directive', {...})

二、开发注意事项

1. 响应式相关问题

// ❌ Vue2 模式
this.$set(this.obj, 'newProp', value)

// ✅ Vue3 可以直接赋值
state.obj.newProp = value

// 注意:解构会丢失响应式
const { count } = state // 失去响应式
// 应使用 toRefs
const { count } = toRefs(state)

2. v-model 变化

<!-- Vue2: 多个 v-model 需要手动处理 -->
<ChildComponent v-model="value" :other.sync="otherValue" />

<!-- Vue3: 支持多个 v-model -->
<ChildComponent v-model:title="title" v-model:content="content" />

3. 全局挂载方式

// Vue2
Vue.prototype.$axios = axios

// Vue3
const app = createApp(App)
app.config.globalProperties.$axios = axios

4. 新增组件/特性注意事项

  • Fragment: 组件可以有多根节点,但需要显式定义属性透传策略
  • Teleport: 使用 to 属性指定挂载位置,注意 SSR 兼容性
  • Suspense: 实验性特性,谨慎在生产环境使用

5. 性能优化注意点

// 大数组性能优化:使用 shallowRef/shallowReactive
const largeArray = shallowRef([...]) // 只追踪整体替换

// 组件渲染优化:v-memo(Vue3.2+)
<div v-for="item in list" :key="item.id" v-memo="[item.id]">
  {{ item.name }}
</div>

6. TypeScript 支持

  • Vue3 原生 TS 支持更好,但需要在 script 标签声明 lang="ts"
  • definePropsdefineEmits 需要显式声明类型

7. 移除的特性

  • $children(使用 $refs 替代)
  • $on$off$once(事件总线需使用第三方库)
  • filter(使用 computed 或 method 替代)
  • inline-template 属性

8. 迁移注意事项

// mixin 冲突处理优先级变化
// 自定义指令生命周期钩子名称变化
bind → beforeMount
inserted → mounted
update → 移除,使用 updated

// keyCode 修饰符移除
// ❌ @keyup.13
// ✅ 使用键名 @keyup.enter

三、推荐开发实践

  1. 新项目直接使用 Vue3 + Composition API + <script setup>
  2. 从 Vue2 迁移时,使用 @vue/compat 进行渐进式迁移
  3. 使用 Vite 代替 Vue CLI 获得更好的开发体验
  4. Pinia 替代 Vuex 作为状态管理方案
  5. 利用 Vue3 的 tree-shaking 减小打包体积

这些变化整体提升了开发体验、性能和类型支持,但需要熟悉新的 API 和最佳实践。

×
BaiqiCMS官方客服

添加BaiqiCMS官方微信客服

关闭