vue2 升级 vue3指南

注册全局组件

2.0:

Vue.component('UITreeBase', UITreeBase)

3.0:

const app = createApp(App)
// 作为全局组件避免交叉引用
app.component('UITreeBase', UITreeBase)

Vuex

import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
modules: {
design,
user
}
})

3.0:

import { createStore } from 'vuex'
export default createStore({
modules: {
design,
user
}
})

computed中的mapState

import { mapState } from 'vuex'
computed: {
…mapState({
sideBars: (state: any) => state.design.leftSidebars,
leftSidebarMinWidth: (state: any) => state.design.leftSidebarMinWidth,
pageScale: (state: any) => state.design.scale
})
}

3.0

const leftSidebarMinWidth = computed((ctx: any) => ctx.$store.state.design.leftSidebarMinWidth)
const leftSidebarWidth = computed({
get () {
return this.$store.state.design.leftSidebarWidth
},
set (v: number) {
this.$store.commit('updateState', { leftSidebarWidth: v })
}
})

setup中的this

import { ref, reactive, computed, watch, onMounted, getCurrentInstance } from 'vue'
const { ctx } = getCurrentInstance()

store

2.0 调用store是直接通过this.$store.commit/dispatch

3.0

import { useStore } from 'vuex'
const store = useStore()
store.commit('updateState', { rightSidebarIsOpen: v })


如果是要使用$store的话,需要在src目录下面创建一个shims-vux.d.ts文件,内容如下

import { Store } from 'vuex'
import { State } from './store'

declare module '@vue/runtime-core' {
  interface ComponentCustomProperties {
    $store: Store<State>
  }
}



// Vuex@4.0.0-beta.1 is missing the typing for `useStore`. See https://github.com/vuejs/vuex/issues/1736

declare module 'vuex' {
  export function useStore(key?: string): Store<State>
}

注意:.$store用法虽然能编译通过,但似乎并不能想期望的2.0那样工作;useStore()在setup里面调用,如果在方法里面调用,或则在computed的get,set里面调用useStore()返回的是undefined

$refs

2.0 直接用this.$refs.XXX引用

3.0 直接需要const refName = ref(), 然后setup中返回refName即可,refName就是ref=“refName”中的名字

$nextTick

import { nextTick } from 'vue'

Vue.component

2.x 动态注册组件

Vue.component(
name,
(resolve) => {
// console.log(`@/components/ui/${this.ui}_${this.uiVersion}/${this.uiconfig.type}.vue`)
require([`@/components/ui/${this.ui}_${this.uiVersion}/${this.uiconfig.type}.vue`], resolve)
}
)

Vue.config.productionTip

3.x 已删除该选项

Write operation failed: computed value is readonly

这个警告有几种情况:

  1. 对应computed没有定义set, 定义对应的set即可
  2. store中使用了[]语法,比如state[name] = value: