Vue3 + TS初探

127 阅读2分钟

安装

通过脚手架vue-cli:
npm install -g @vue/cli # 或 yarn global add @vue/cli
vue create hello-vue3
# 选择 Manually select features
# 根据自己所需选择功能

项目目录

.
├── babel.config.js
├── package.json
├── public
├── src
│   ├── App.vue
│   ├── api
│   │   ├── commjs.js
│   │   ├── myFindWorkCard.js
│   │   └── works.js
│   ├── assets
│   │   ├── common.less
│   │   ├── font
│   │   ├── image
│   │   ├── mixins.less
│   │   └── theme.less
│   ├── business
│   │   ├── const.ts
│   │   ├── dataTrans.js
│   │   ├── pageAnimate.ts
│   │   └── requestTip.js
│   ├── components
│   ├── config
│   │   └── index.ts
│   ├── main.ts
│   ├── router
│   │   └── index.ts
│   ├── shims-vue.d.ts
│   ├── store
│   │   ├── index.js
│   │   └── module
│   ├── types
│   │   ├── const.ts
│   │   ├── index.d.ts
│   │   └── route.ts
│   ├── use
│   │   └── useUserInfo
│   │       └── index.ts
│   ├── utils
│   └── views
│       ├── findjobs
│       │   ├── index.less
│       │   └── index.vue
│       ├── login
│       │   └── index.vue
│       └── mine
│           └── index.vue
├── tsconfig.json
├── tslint.json
├── vue.config.js
└── yarn.lock
增加types目录统一管理type文件,方便后期维护

新特性

组合式 API

使用:
setup(props, context) {
    console.log(props, context)

    return {} // 这里返回的任何内容都可以用于组件的其余部分
  }
  setup执行时实例还未创建,所以你将无法访问组件声明的任何属性
  但是可以通过api getCurrentInstance获取到当前实例

全局方法属性

main.ts 
const app = createApp(App)
app.config.globalProperties.$filters = {
  mapTrans (value:string, obj:object) {
    return obj[value]
  }
}
获取:
getCurrentInstance().appContext.config.globalProperties.$filters

注册全局组件

main.tsimport myComponent from '@/components/index'
myComponent(app)

@/components/index:
import myTop from '@/components/myTop/index.vue'
const myComponent = function (app:any) {
  app.component('my-top', myTop)
}
export default myComponent

组合式API

setup和minxin类似,但是mixin容易造成上下文混乱不方便维护
ref:是某个值成为响应式数据,返回一个Proxy对象,设置值x.value = xx 
reactive:是某个对象成为响应式数据,设置值x = xx
生命周期钩子:setup函数中注册不同生命周期的回调函数
返回值:Object|Funtion 返回一个对象在组件模板可直接访问;或者返回一个render函数
在setup函数中可以抽离公共代码逻辑,类似React hooks,方便后期维护,简单的来说现在在一个setup函数中可以用vue实例的特性,比如响应式数据、computed、watch、生命钩子函数等

组件

异步组件注册:
比如在路由中使用 {
    path: '/mine',
    name: 'mine',
    component: defineAsyncComponent(() =>
      import('@/views/mine/index.vue')
    ),
    meta:{title:'我'}
}

自定义事件注册:
export default {
    props: ['text'],
    emits: ['accepted']
  }

其他小改动

全局API:现在挂载到了实例const app = createApp({})上
片段:Vue3支持多根节点
Teleport:可指定当前节点渲染的父节点
v-for:
mixin:现在是浅合并,在组件data中没有声明的属性不会再合并过来
...