完整的 Vue 2 + TypeScript + Vuex 的项目案例

下面是一个完整的 Vue 2 + TypeScript + Vuex 的项目案例。这个示例包括了基本的项目结构、Vuex 模块、组件和路由配置。

项目结构

src/

├── assets/

├── components/

│ └── Counter.vue

├── router/

│ └── index.ts

├── store/

│ ├── index.ts

│ └── modules/

│ └── counter.ts

├── App.vue

└── main.ts

  1. 安装依赖

首先确保安装了必要的依赖:

bash 复制代码
npm install vue vuex vue-router @types/node typescript ts-loader
  1. 配置 tsconfig.json

在项目根目录下创建 tsconfig.json 文件

javascript 复制代码
{
  "compilerOptions": {
    "target": "es5",
    "module": "esnext",
    "strict": true,
    "jsx": "preserve",
    "importHelpers": true,
    "moduleResolution": "node",
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "sourceMap": true,
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    },
    "lib": ["esnext", "dom", "dom.iterable", "scripthost"]
  },
  "include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"],
  "exclude": ["node_modules"]
}
  1. 配置 main.ts

在 src/main.ts 中配置 Vue 应用:

TypeScript 复制代码
import Vue from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';

Vue.config.productionTip = false;

new Vue({
  router,
  store,
  render: h => h(App),
}).$mount('#app');
  1. 配置 Vuex 存储

在 src/store/index.ts 中配置 Vuex 存储:

TypeScript 复制代码
import Vue from 'vue';
import Vuex from 'vuex';
import counter from './modules/counter';

Vue.use(Vuex);

export default new Vuex.Store({
  modules: {
    counter,
  },
});

在 src/store/modules/counter.ts 中定义 counter 模块:

TypeScript 复制代码
import { Module, ActionContext } from 'vuex';

interface State {
  count: number;
}

const counter: Module<State, any> = {
  state: (): State => ({
    count: 0,
  }),
  mutations: {
    increment(state: State) {
      state.count++;
      console.log('increment:', state.count);
    },
  },
  getters: {
    doubleCount: (state: State) => state.count * 2,
  },
  actions: {
    asyncIncrement({ commit }: ActionContext<State, any>) {
      setTimeout(() => {
        commit('increment');
      }, 1000);
    },
  },
};

export default counter;
  1. 配置路由

在 src/router/index.ts 中配置路由:

TypeScript 复制代码
import Vue from 'vue';
import VueRouter from 'vue-router';
import Counter from '../components/Counter.vue';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'Counter',
    component: Counter,
  },
];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes,
});

export default router;
  1. 创建组件

在 src/components/Counter.vue 中创建 Counter 组件:

TypeScript 复制代码
<template>
  <div>
    <h1>Counter</h1>
    <p>Count: {{ count }}</p>
    <p>Double Count: {{ doubleCount }}</p>
    <button @click="increment">Increment</button>
    <button @click="asyncIncrement">Async Increment</button>
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';
import { mapState, mapGetters, mapActions } from 'vuex';

@Component({
  computed: {
    ...mapState(['count']),
    ...mapGetters(['doubleCount']),
  },
  methods: {
    ...mapActions(['increment', 'asyncIncrement']),
  },
})
export default class Counter extends Vue {}
</script>

<style scoped>
button {
  margin: 5px;
}
</style>
  1. 创建 App.vue

在 src/App.vue 中创建主应用组件:

TypeScript 复制代码
<template>
  <div id="app">
    <router-view />
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';

@Component
export default class App extends Vue {}
</script>

<style>
#app {
  font-family: Avenir, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
  1. 运行项目

最后,运行项目:

bash 复制代码
npm run serve

这个示例展示了如何在 Vue 2 项目中使用 TypeScript 和 Vuex。你可以根据需要扩展和修改这个基础结构。

相关推荐
玩电脑的辣条哥2 小时前
Python如何播放本地音乐并在web页面播放
开发语言·前端·python
ew452182 小时前
ElementUI表格表头自定义添加checkbox,点击选中样式不生效
前端·javascript·elementui
suibian52352 小时前
AI时代:前端开发的职业发展路径拓宽
前端·人工智能
画月的亮2 小时前
element-ui 使用过程中遇到的一些问题及解决方法
javascript·vue.js·ui
Moon.92 小时前
el-table的hasChildren不生效?子级没数据还显示箭头号?树形数据无法展开和收缩
前端·vue.js·html
m0_526119402 小时前
点击el-dialog弹框跳到其他页面浏览器的滚动条消失了多了 el-popup-parent--hidden
javascript·vue.js·elementui
垚垚 Securify 前沿站2 小时前
深入了解 AppScan 工具的使用:筑牢 Web 应用安全防线
运维·前端·网络·安全·web安全·系统安全
工业甲酰苯胺5 小时前
Vue3 基础概念与环境搭建
前端·javascript·vue.js
lyj1689975 小时前
el-tree选中数据重组成树
javascript·vue.js·elementui
mosquito_lover16 小时前
怎么把pyqt界面做的像web一样漂亮
前端·python·pyqt