vue3.x +ts- 使用记录,踩坑
1.安装
// 全局安装vue/cli npm install -g @vue/cli // 更新 vue upgrade --next // 安装项目 npm init vite-app my-app cd my-app npm i npm run dev
2.引入axios
npm install axios -S //main.js 引入 import axios from 'axios'; const app = createApp(App); app.config.globalProperties.$axios = axios; app.mount('#app');
loadsh 同axios
1. 访问实例用 getCurrentInstance()
import {ComponentInternalInstance, getCurrentInstance} from "vue"; /** * proxy 用到地方很多,但是ts中直接调用getCurrentInstance会报错 ComponentInternalInstance | null,所以二次封装 */ export const useCurrentInstance = () => { const {appContext} = getCurrentInstance() as ComponentInternalInstance; return { proxy: appContext.config.globalProperties }; };
2. 访问VUEX a.import {useStore} from 'vuex'; b.setup中使用 setup(){const store = useStore();console.log(store)// 即可访问vuex}
//test.vue import { useStore } from 'vuex' setup() { const {proxy} = useCurrentInstance(); const store = useStore(); onMounted(() => { console.log(store.state.count); console.log(proxy.$store.state.count); }); }, // store.ts import {createStore} from "vuex"; export default createStore({ state: { count: 1 }, mutations: {}, actions: {}, modules: {} });
· 在main.ts中引入依赖总是报错,比如lodash,报错<code> can not found module ''</code>
解决方法: 在root下有个文件<code>shims-vue.d.ts</code>,在地面加上<code>declare module 'lodash'</code>,重启,就不会报错了
/* eslint-disable */ declare module "*.vue" { import type {DefineComponent} from "vue"; const component: DefineComponent<{}, {}, any>; export default component; } declare module "lodash";
. vue3已经废弃了slot='test',所以在使用中,会报错<code>ionic - `slot` attributes are deprecated - eslint-plugin-vue</code>;解决方案:
module.exports = { root: true, env: { node: true }, 'extends': [ 'plugin:vue/vue3-essential', 'eslint:recommended', '@vue/typescript/recommended' ], parserOptions: { ecmaVersion: 2020 }, rules: { 'no-console': process.env.NODE_ENV === 'production' ? 'warn' : 'off', 'no-debugger': process.env.NODE_ENV === 'production' ? 'warn' : 'off', 'vue/no-deprecated-slot-attribute': 'off', '@typescript-eslint/no-explicit-any': 'off', }, overrides: [ { files: [ '**/__tests__/*.{j,t}s?(x)', '**/tests/unit/**/*.spec.{j,t}s?(x)' ], env: { jest: true } } ] }
地址: https://github.com/ionic-team/ionic-framework/issues/22236