-
項目運行環境
node v12.9.0
npm v6.10.2
cli-service v4.5.0 -
核心框架版本號
"vue": "^3.0.0",
"vue-class-component": "^8.0.0-0",
"vue-router": "^4.0.0-0",
"vuex": "^4.0.0-0",
"vuex-class": "^0.3.2" -
vue實例掛載
import { createaApp } from "vue"
let app = createaApp(...)
app.mount("#app")
4.如何獲取組件 ref
- 如何注冊全局方法
比較常見的一種方式就是掛載vue的原型上
vue2
// common.js
export default {
install(Vue){
Vue.prototype.$loginInfo = loginInfo;
}
}// main.js
vue.use(common)vue3 + ts
申明類型
// common.tsdeclare module '@vue/runtime-core' {
interface ComponentCustomProperties {
$loginInfo = loginInfo
}
}掛載到 globalProperties
// common.ts
import { App } from 'vue';declare module '@vue/runtime-core' {
interface ComponentCustomProperties {
$loginInfo = loginInfo
}
}export default {
install(app: App) {
app.config.globalProperties.$loginInfo = loginInfo
}
}注冊全局方法
import { createaApp } from "vue"
let app = createaApp(...)app.use(common) //注冊
app.mount("#app")- setup + vue-class-component
vue-class-component v8版本的文檔還沒出來,具體語法規則可以查看項目的 issues 或者 源碼
@Component will be renamed to @Options.
@Options is optional if you don't declare any options with it.
Vue constructor is provided from vue-class-component package.
Component.registerHooks will move to Vue.registerHooks- Vuex + vue-class-component
生成唯一標識key
import { InjectionKey } from "vue"
export const key: InjectionKey<Store
> = Symbol()
關聯 key 與 storeimport { createaApp } from "vue"
import {store, key } from "./store"
let app = createaApp(...)app.use(store, key)
app.mount("#app")
使用 vueximport { namespace } from "vuex-class";
const moduleAny = namespace("moduleName");export default class AnyCom extends Vue {
@moduleAny.State("token") public token?: any;
@moduleAny.Mutation("getToken") public getToken!: Function;
create(){ console.log(this.getToken()) }
}
項目的根目錄增加全局類型文件 vuex.d.tsimport { ComponentCustomProperties } from 'vue'
import { Store } from 'vuex'declare module '@vue/runtime-core' {
// declare your own store states
interface State {
//
}
// provide typings forthis.$store
interface ComponentCustomProperties {
$store: Store
}
}- vuex + setup
import {useStore } from "vuex"
import { key } from '@/store/index'const store = useStore(key);
store.dispatch('moduleName/query')- cli-service 配置,不打包Vue axios vuex vue-router 等
configureWebpack: {
externals: {
'vue': 'Vue',
'vue-router': 'VueRouter',
'vuex': 'Vuex',
'axios': 'axios'
},
}, - 如何注冊全局方法