当前位置: 首页 > news >正文

如何在 Vue 3 中使用 Vue Router 和 Vuex

在 Vue 3 中使用 Vue Router

1. 安装 Vue Router

在项目根目录下,通过 npm 或 yarn 安装 Vue Router 4(适用于 Vue 3):

npm install vue-router@4
# 或者使用 yarn
yarn add vue-router@4
2. 创建路由配置文件

src 目录下创建一个 router 文件夹,并在其中创建 index.js 文件,用于配置路由:

// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue'; // 假设 Home 组件在 views 文件夹下
import About from '../views/About.vue'; // 假设 About 组件在 views 文件夹下

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: About
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

export default router;
3. 在主应用中使用路由

main.js 中引入并使用路由:

// src/main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';

const app = createApp(App);
app.use(router);
app.mount('#app');
4. 在模板中使用路由

App.vue 中添加路由出口和导航链接:

<template>
  <div>
    <!-- 导航链接 -->
    <router-link to="/">Home</router-link>
    <router-link to="/about">About</router-link>

    <!-- 路由出口,用于显示当前路由对应的组件 -->
    <router-view></router-view>
  </div>
</template>

<script setup>
// 这里可以添加其他逻辑
</script>

<style scoped>
/* 样式 */
</style>
5. 路由导航守卫(可选)

可以使用路由导航守卫来控制路由的访问权限等,例如在 router/index.js 中添加全局前置守卫:

// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import Home from '../views/Home.vue';
import About from '../views/About.vue';

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home
  },
  {
    path: '/about',
    name: 'About',
    component: About
  }
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 可以在这里添加权限验证等逻辑
  console.log('Before each navigation');
  next();
});

export default router;

在 Vue 3 中使用 Vuex(Vuex 4 适用于 Vue 3)

1. 安装 Vuex

在项目根目录下,通过 npm 或 yarn 安装 Vuex 4:

npm install vuex@4
# 或者使用 yarn
yarn add vuex@4
2. 创建 store

src 目录下创建一个 store 文件夹,并在其中创建 index.js 文件,用于创建和配置 store:

// src/store/index.js
import { createStore } from 'vuex';

const store = createStore({
  state() {
    return {
      count: 0
    };
  },
  mutations: {
    increment(state) {
      state.count++;
    },
    decrement(state) {
      state.count--;
    }
  },
  actions: {
    incrementAsync(context) {
      setTimeout(() => {
        context.commit('increment');
      }, 1000);
    }
  },
  getters: {
    doubleCount(state) {
      return state.count * 2;
    }
  }
});

export default store;
3. 在主应用中使用 store

main.js 中引入并使用 store:

// src/main.js
import { createApp } from 'vue';
import App from './App.vue';
import router from './router';
import store from './store';

const app = createApp(App);
app.use(router);
app.use(store);
app.mount('#app');
4. 在组件中使用 store

在组件中可以通过不同方式使用 store 中的状态、mutations、actions 和 getters:

<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Double Count: {{ doubleCount }}</p>
    <button @click="increment">Increment</button>
    <button @click="decrement">Decrement</button>
    <button @click="incrementAsync">Increment Async</button>
  </div>
</template>

<script setup>
import { useStore } from 'vuex';

const store = useStore();

const count = store.state.count;
const doubleCount = store.getters.doubleCount;

const increment = () => {
  store.commit('increment');
};

const decrement = () => {
  store.commit('decrement');
};

const incrementAsync = () => {
  store.dispatch('incrementAsync');
};
</script>

<style scoped>
/* 样式 */
</style>

通过以上步骤,你就可以在 Vue 3 项目中成功使用 Vue Router 和 Vuex 了。在实际开发中,你可以根据项目需求进一步扩展和优化路由配置和 store 逻辑。

相关文章:

  • 联想小新 510S-14IKB (80UX) 原厂Win10系统oem镜像下载
  • Hive查询之排序
  • 面试题整理:操作系统
  • Python 用户输入和While循环(使用while 循环来处理列表和字典)
  • PerfMonitor高效处理器性能监控与分析利器
  • [实现Rpc] 客户端划分 | 框架设计 | common类的实现
  • React AJAX:深入理解与高效实践
  • Java 数据类型
  • pptx2md - 将PPT文件转换成Markdown
  • 从零搭建微服务项目(第7章——微服务网关模块基础实现)
  • 如何解决DeepSeek服务器繁忙的问题?
  • JUC并发-4.wait和notify以及Atomic原理
  • 【JavaWeb学习Day16】
  • 什么是scaling laws?
  • 实现MiniQMT远程下单:跨设备交易指令的高效传递
  • pnpm, eslint, vue-router4, element-plus, pinia
  • Spring AOP源码解析
  • 【RocketMQ 存储】CommitLogDispatcherBuildConsumeQueue 构建 ConsumeQueue 索引
  • 基于 Ollama 工具的 LLM 大语言模型如何部署,以 DeepSeek 14B 本地部署为例
  • Web 后端 HTTP协议
  • “走进书适圈”:一周城市生活
  • 广西等地旱情缓解,水利部针对甘肃启动干旱防御Ⅳ级响应
  • 刘强东坐镇京东一线:管理层培训1800人次,最注重用户体验
  • 终于越过萨巴伦卡这座高山,郑钦文感谢自己的耐心和专注
  • 国务院办公厅印发《国务院2025年度立法工作计划》
  • 专访|茸主:杀回UFC,只为给自己一个交代