vue.js

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript类库 > vue.js > Vue3引用TS语法

Vue3项目中引用TS语法的实例讲解

作者:灬ManongLai

这篇文章主要介绍了Vue3项目中引用TS语法的实例讲解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

基础语法

定义data 

//script标签上 **lang="ts"**
<script lang="ts">
import { defineComponent, reactive, ref, toRefs } from 'vue';
//定义一个类型type或者接口interface来约束data
type Todo = {
  id: number,
  name: string,
  completed: boolean
}
export default defineComponent({
    //使用reactive时,可以用toRefs解构导出,在template就可以直接使用了
    const data = reactive({
      todoList: [] as Todo[]
    })
    //可以使用ref或者toRefs来定义响应式数据
    const count = ref(0);
    //使用ref在setup读取的时候需要获取xxx.value,但在template中不需要
    console.log(count.value)
    return {
      ...toRefs(data)
    }
})
</script>

定义props

import { defineComponent, PropType} from 'vue';
interface UserInfo = {
  id: number,
  name: string,
  age: number
}
export default defineComponent({
//props需要使用PropType泛型来约束。
  props: {
    userInfo: {
      type: Object as PropType<UserInfo>, // 泛型类型
      required: true
    }
  },
})

定义methods 

import { defineComponent, reactive, ref, toRefs } from 'vue';
type Todo = {
  id: number,
  name: string,
  completed: boolean
}
export default defineComponent({
  const data = reactive({
    todoList: [] as Todo[]
  })
  // 约束输入和输出类型
  const newTodo = (name: string):Todo  => {
    return {
      id: this.items.length + 1,
      name,
      completed: false
    };
  }
  const addTodo = (todo: Todo): void => {
    data.todoList.push(todo)
  }
  return {
    ...toRefs(data),
    newTodo,
    addTodo
  }
})

vue-router

import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router';
import Home from '../views/Home.vue';
//routes的约束类型是RouteRecordRaw
const routes: Array< RouteRecordRaw > = [
  {
    path: '/',
    name: 'Home',
    component: Home,
  },
  {
    path: '/about',
    name: 'About',
    component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
  }
];
//createRouter创建router实例
const router = createRouter({
//router的模式分为
    //createWebHistory -- history模式
    //createWebHashHistory -- hash模式
  history: createWebHistory(process.env.BASE_URL),
  routes
});
export default router;

扩展路由额外属性

// 联合类型
//在实际项目开发中,常常会遇到这么一个场景
//某一个路由是不需要渲染到侧边栏导航上的
//此时我们可以给该路由添加一个hidden属性来实现。
//在ts的强类型约束下,添加额外属性就会报错,那么我们就需要扩展RouteRecordRaw类型。
type RouteConfig = RouteRecordRaw & {hidden?: boolean}; //hidden 是可选属性
const routes: Array<RouteConfig> = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    hidden: true,
    meta: {
      permission: true,
      icon: ''
    }
  }
];

在setup中使用

//需要导入useRouter创建一个router实例。
import { useRouter } from 'vue-router';
import { defineComponent } from 'vue';
export default defineComponent({
  setup () {
    const router = useRouter();
    goRoute(path) {
       router.push({path})
    }
  }
})

vuex#####

使用this.$store 

import { createStore } from 'vuex';
export type State = {
  count: number
}
export default createStore({
  state: {
    count: 0
  }
});
import {ComponentCustomProperties} from 'vue';
import {Store} from 'vuex';
import {State} from './store'
declare module '@vue/runtime-core' {
    interface ComponentCustomProperties {
        $store: Store<State>
    }
}

在setup中使用

import { InjectionKey } from 'vue';
import { createStore, Store } from 'vuex';
export type State = {
  count: number
}
// 创建一个injectionKey
export const key: InjectionKey<Store<State>> = Symbol('key');
// main.ts
import store, { key } from './store';
app.use(store, key);
import { useStore } from 'vuex';
import { key } from '@/store';
export default defineComponent({
  setup () {
    const store = useStore(key);
    const count = computed(() => store.state.count);
    return {
      count
    }
  }
})

模块

import { Module } from 'vuex';
import { State } from '../index.ts';
type Todo = {
  id: number,
  name: string,
  completed: boolean
}
const initialState = {
  todos: [] as Todo[]
};
export type TodoState = typeof initialState;
export default {
  namespaced: true,
  state: initialState,
  mutations: {
    addTodo (state, payload: Todo) {
      state.todos.push(payload);
    }
  }
} as Module<TodoState, State>; //Module<S, R> S 该模块类型 R根模块类型
// index.ts
export type State = {
  count: number,
  todo?: TodoState // 这里必须是可选,不然state会报错
}
export default createStore({
  state: {
    count: 0
  }
  modules: {
    todo
  }
});
setup () {
  console.log(store.state.todo?.todos);
}

elementPlus

yarn add element-plus

完整引入

import { createApp } from 'vue'
import ElementPlus from 'element-plus';import 'element-plus/lib/theme-chalk/index.css';import App from './App.vue';
import 'dayjs/locale/zh-cn'
import locale from 'element-plus/lib/locale/lang/zh-cn'
const app = createApp(App)
app.use(ElementPlus, { size: 'small', zIndex: 3000, locale })
app.mount('#app')

按需加载

yarn add babel-plugin-component -D
// babel.config.js
plugins: [
    [
      'component',
      {
        libraryName: 'element-plus',
        styleLibraryName: 'theme-chalk'
      }
    ]
]
import 'element-plus/lib/theme-chalk/index.css';
import 'dayjs/locale/zh-cn';
import locale from 'element-plus/lib/locale';
import lang from 'element-plus/lib/locale/lang/zh-cn';
import {
  ElAside,
  ElButton,
  ElButtonGroup,
} from 'element-plus';
const components: any[] = [
  ElAside,
  ElButton,
  ElButtonGroup,
];
const plugins:any[] = [
  ElLoading,
  ElMessage,
  ElMessageBox,
  ElNotification
];
const element = (app: any):any => {
  // 国际化
  locale.use(lang);
  // 全局配置
  app.config.globalProperties.$ELEMENT = { size: 'small' };
  
  components.forEach(component => {
    app.component(component.name, component);
  });
  plugins.forEach(plugin => {
    app.use(plugin);
  });
};
export default element;
// main.ts
import element from './plugin/elemment'
const app = createApp(App);
element(app);

axios

type Config = AxiosRequestConfig & {successNotice? : boolean, errorNotice? : boolean}
import axios, { AxiosResponse, AxiosRequestConfig } from 'axios';
import { ElMessage } from 'element-plus';
const instance = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL || '',
  timeout: 120 * 1000,
  withCredentials: true
});
// 错误处理
const err = (error) => {
  if (error.message.includes('timeout')) {
    ElMessage({
      message: '请求超时,请刷新网页重试',
      type: 'error'
    });
  }
  if (error.response) {
    const data = error.response.data;
    if (error.response.status === 403) {
      ElMessage({
        message: 'Forbidden',
        type: 'error'
      });
    }
    if (error.response.status === 401) {
      ElMessage({
        message: 'Unauthorized',
        type: 'error'
      });
    }
  }
  return Promise.reject(error);
};
type Config = AxiosRequestConfig & {successNotice? : boolean, errorNotice? : boolean}
// 请求拦截
instance.interceptors.request.use((config: Config) => {
  config.headers['Access-Token'] = localStorage.getItem('token') || '';
  return config;
}, err);
// 响应拦截
instance.interceptors.response.use((response: AxiosResponse) => {
  const config: Config = response.config;
  const code = Number(response.data.status);
  if (code === 200) {
    if (config && config.successNotice) {
      ElMessage({
        message: response.data.msg,
        type: 'success'
      });
    }
    return response.data;
  } else {
    let errCode = [402, 403];
    if (errCode.includes(response.data.code)) {
      ElMessage({
        message: response.data.msg,
        type: 'warning'
      });
    }
  }
}, err);
export default instance;

setup script

<template>
  <div>
    {{count}}
    <ImgReview></ImgReview >
  </div>
</template>
<script lang="ts">
import { ref, defineComponent } from "vue";
import ImgReview from "./components/ImgReview.vue";
export default defineComponent({
  components: {
    ImgReview,
  },
  setup() {
    const count = ref(0);
    return { count };
  }
});
</script>
<template>
  <div>
    {{count}}
    <ImgReview></ImgReview>
  </div>
</template>
<script lang="ts" setup>
    import { ref } from "vue";
    import ImgReview from "./components/ImgReview.vue";
    const count = ref(0);
</script>

导出方法

const handleClick = (type: string) => {
  console.log(type);
}

定义props

import { defineProps } from "vue";
const props = defineProps(['userInfo', 'gameId']);
const props = defineProps({
  gameId: Number,
  userInfo: {
      type: Object,
      required: true
  }
});
defineProps<{
  name: string
  phoneNumber: number
  userInfo: object
  tags: string[]
}>()
interface UserInfo {
  id: number,
  name: string,
  age: number
}
defineProps<{
  name: string
  userInfo: UserInfo
}>()

defineEmit

import { defineEmit } from 'vue';
// expects emits options
const emit = defineEmit(['kk', 'up']);
const handleClick = () => {
  emit('kk', '点了我');
};
<Comp @kk="handleClick"/>
<script lang="ts" setup>
const handleClick = (data) => {
  console.log(data)
}
</script>

获取上下文

 import { useContext } from 'vue'
 const { slots, attrs } = useContext();

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文