mynote/vue/vue3.md
2022-06-05 10:19:11 +08:00

181 lines
2.9 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# vue3 typescript vue-router vuex setup
## 使用模板
```bash
npx degit veypi/vite-starter#master project_name
```
### 最近发现vue3相关库都更新的差不多了尝试学习了新的版本, 使用setup 的确变了很多像ref 、prop面目全非刚开始用还找了很久
## 创建项目
```bash
yarn create vite name --template vue-ts
```
### [vue-router](https://next.router.vuejs.org/zh/installation.html)
```bash
# 安装
npm install vue-router@4
```
```typescript
// vim router/index.ts
import { createRouter, createWebHistory } from 'vue-router'
const router = createRouter({
history: createWebHistory(),
routes: [
{
path: '/',
name: 'home',
component: () => import('../view/file.vue')
},
{
path: '/t',
name: 't',
component: () => import('../view/file.vue')
}
//...
],
})
export default router
```
### tailwindcss
```bash
npm install -D tailwindcss@latest postcss@latest autoprefixer@latest
npx tailwindcss init -p
```
### [vuex](https://next.vuex.vuejs.org/zh/guide/typescript-support.html)
```bash
# 安装
yarn add vuex@next --save
```
```typescript
// store/index.ts
import { InjectionKey } from 'vue'
import { createStore, useStore as baseUseStore, Store } from 'vuex'
export interface State {
count: number
}
export const key: InjectionKey<Store<State>> = Symbol()
export const store = createStore<State>({
state: {
count: 0
},
mutations: {
increment(state) {
state.count ++
}
},
actions: {
asd(context) {
context.commit('increment')
}
}
})
// 定义自己的 `useStore` 组合式函数
export function useStore () {
return baseUseStore(key)
}
```
### main.ts
```typescript
import {createApp} from 'vue'
import App from './App.vue'
import router from './router'
import {store, key} from './store'
const app = createApp(App)
app.use(router)
app.use(store, key)
app.mount('#app')
```
## 使用技巧
```typescript
// prop vue3 v-module 绑定的事件名改了
// setup
let emits = defineEmits<{
(e: 'update:modelValue', v: boolean): void
}>()
let props = defineProps<{
modelValue: boolean
}>()
function setValue(b: boolean) {
emits('update:modelValue', b)
}
```
```typescript
// slots 中默认插槽
// props 允许为空的写法, 否则会报错
import {computed, useSlots, withDefaults} from 'vue'
const slots = useSlots()
const icon = computed(() => {
// @ts-ignore
if (slots.default) return slots.default()[0].children?.trim()
return ''
})
const props = withDefaults(defineProps<{
color?: string
}>(), {
color: ''
})
```
```typescript
// webstorm 识别路径别名@
// 在tsconfig.json complierOptions 下添加
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
// vite.config.js
resolve: {
// https://vitejs.dev/config/#resolve-alias
alias: {
"@": "/src",
},
},
```