vue3中使用ts

一、选项式api中使用ts

使用defineComponent定义组件 => 启用类型推导

<template>
  <div>
    <h2>Hello 01</h2>
    <button @click="handleClick(5)">点击</button>
    {{ count }}, {{ doubleCount }}
  </div>
</template>

<script lang="ts">
import { defineComponent } from 'vue'

type Count = number | string;
interface List {
  username: string
  age: number
}
export default defineComponent({
  data(){
    return {
      count: 0 as Count,
      list: [] as List[]
    }
  },
  mounted(){
    this.count = 2
    this.list.push({
      username: 'xiaoming',
      age: 20
    });
  },
  computed: {
    doubleCount(): number|string{
      if(typeof this.count === 'number'){
        return this.count * 2;
      }
      else{
        return this.count;
      }
    }
  },
  methods: {
    handleClick(n: number){
      if(typeof this.count === 'number'){
        this.count += n;
      }
    }
  }
});
</script>

<style scoped>

</style>

二、组件通信中使用ts

父子通信

import { defineComponent } from 'vue'
import type { PropType } from 'vue'

interface List {
  username: string
  age: number
}

export default defineComponent({
  props: {
    count: [Number, String],
    list: Object as PropType<List[]>
  },
  //emits: ['get-data'],
  emits: {
    'get-data'(payload: string){ return payload.length > 0 }
  },
  mounted(){
    this.$emit('get-data', 'hello');
  }
})

三、组合式api中使用ts

compositionApi默认启用了类型检测,定义基本类型数据可以使用泛型的形式绑定类型

<template>
  <div>
    <h2>Hello 03</h2>
    <button @click="handlClick(5)">点击</button>
    {{ count }}, {{ doubleCount }}
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue';


// let count = ref<number|string>(0); 
// count.value = 'hello';

// interface List {
//   username: string
//   age: number
// }

// let list = ref<List[]>([]);

// list.value.push({
//   username: 'xiaoming',
//   age: 20
// });

let count = ref(0);
let doubleCount = computed(()=> count.value * 2);
let handlClick = (n: number) => {
  count.value += n;
}

</script>

<style scoped>

</style>

四、组合式api中组件通信使用ts

父子通信 => defineProps + 泛型
子父通信 => defineEmits + 泛型

<template>
  <div>
    Head Component
  </div>
</template>

<script setup lang="ts">
// import { defineProps, defineEmits } from 'vue'

// 1. 
// defineProps({
//   count: [Number, String]
// });

//2. 
interface Props {
  count: number|string
  list: {username: string; age: number}[]
}

interface Emits {
  (e: 'get-data', payload: string): void
}

defineProps<Props>();

let emit = defineEmits<Emits>();

emit('get-data', 'hello');
</script>

<style scoped>

</style>

五、vueRouter中使用ts

路由中使用ts 路由表的类型和路由中的meta类型需要手动处理一下,其他地方(createRouter、useRoute、useRouter)默认已经处理好了

import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import HomeView from '../views/HomeView.vue'

declare module 'vue-router' {
  interface RouteMeta {
    // 是可选的
    isAdmin?: boolean
    // 每个路由都必须声明
    requiresAuth: boolean
  }
}

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: HomeView,
    meta: { requiresAuth: true }
  },
  {
    path: '/about',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes,
})

// router.beforeEach((to, from, next)=>{
  
// });

export default router

六、vuex中使用ts

import { createStore, useStore as baseUseStore } from 'vuex'
import users from './modules/users'
import type { UsersState } from './modules/users'
import type { Store } from 'vuex'
import type { InjectionKey } from 'vue'

export interface State {
  count: number
}

//	整合其他模块的类型
interface StateAll extends State {
  users: UsersState
}

//	这个key是为了能够在组件中使用vuex能够有正确的类型推断
//	还要在main.ts中 注册vuex插件时传递给vue
//	import store, { key } from './store'
//	app.use(store, key)
export const key: InjectionKey<Store<StateAll>> = Symbol()

export function useStore () {//	重写useStore函数 为了避免每次使用都要传key
  return baseUseStore(key)
}

export default createStore<State>({
  state: {
    count: 1
  },
  getters: {
    doubleCount(state){
      return state.count * 2;
    }
  },
  mutations: {//	默认具有类型推断
    // add(state, payload: number){

    // }
  },
  actions: {
  },
  modules: {
    users
  }
})



//	modules/users.ts

import type { MutationTree, ActionTree, GetterTree } from 'vuex'
import type { State } from '../index'

export interface UsersState {
  username: string
  age: number
}

const state: UsersState = {
  username: 'xiaoming',
  age: 20
};

const mutations: MutationTree<UsersState> = {//	其他模块中需要手动引入MutationTree
  // change(state){
    
  // }
};
const actions: ActionTree<UsersState, State> = {};
const getters: GetterTree<UsersState, State> = {
  doubleAge(state){
    return state.age * 2;
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}

七、Element Plus中使用ts

如果使用了volar插件 需要在tsconfig.json中通过compilerOptions.types指定全局组件类型
“types”: [“element-plus/global”]
这样配置完成之后写代码就有了友好的代码提示

  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue 3使用TypeScript(TS)定义数据的方法有几种。首先,你可以使用defineProps函数来定义组件的props。你可以通过传递一个泛型参数来指定props的类型。例如: ``` import { defineProps } from 'vue'; interface Props { id: number; arr: string[]; } const props = defineProps<Props>(); ``` 在这个例子,我们定义了一个Props接口来指定props的类型,并通过defineProps<Props>()函数来定义props。你可以在Props接口定义每个prop的类型,并在组件使用这些props。 另一种方法是使用ref函数来定义组件的引用实例。你可以通过在ref函数的泛型指定类型来获取组件的类型。例如: ``` import { ref } from 'vue'; import NewsDialog from './components/NewsDialog.vue'; const news = ref<InstanceType<typeof NewsDialog>>(); // 打开消息弹窗 const openNewsDialog = (): void => { news.value?.showDialog(); } ``` 在这个例子,我们使用ref函数来定义NewsDialog组件的引用实例,并使用InstanceType<typeof NewsDialog>来获取组件的类型。然后,我们可以使用news.value来访问组件的方法或属性。 还有一种方法是使用computed函数来定义计算属性。computed函数会自动推导出计算函数的返回值类型。例如: ``` import { ref, computed } from 'vue'; const count = ref(0); const double = computed(() => count.value * 2); const result = double.value.split(''); // 这里会报错,因为double的类型是number // 显式指定类型 const double = computed<number>(() => { // 若返回值不是number类型则会报错 }); ``` 在这个例子,我们使用computed函数定义了一个计算属性double,它返回count的值乘以2。computed函数会自动推导出double的类型为ComputedRef<number>。你也可以通过在computed函数的泛型参数显式指定类型。 最后,如果你想在Vue 3使用provide和inject来实现组件之间的数据传递,你可以使用InjectionKey来指定注入的值的类型。例如: ``` import { provide, inject } from 'vue'; import { InjectionKey } from 'vue'; const key = Symbol() as InjectionKey<string>; provide(key, 'foo'); const foo = inject(key); // foo的类型为string | undefined ``` 在这个例子,我们使用provide函数提供了一个key和一个值'foo'。然后,在另一个组件使用inject函数来获取这个值。你可以使用InjectionKey来指定注入值的类型,并在组件使用这个类型来声明变量。 这些是在Vue 3使用TypeScript定义数据的一些方法。你可以根据具体需求选择使用哪种方法来定义数据。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [vue3.0+TS使用](https://blog.csdn.net/yxlyttyxlytt/article/details/128057058)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值