Vue3中使用vue-router、vuex

1. Vue3程序主入口

import { createApp } from 'vue';
import App from './App.vue'

createApp(App).mount('#app')

2. vue-router 的使用

官方文档

安装4.0版本的vue-router

npm install vue-router@4

示例代码

import { createApp } from 'vue'
import { createRouter, createWebHashHistory } from 'vue-router'

// 1. 定义路由组件.
// 也可以从其他文件导入
const Home = { template: '
Home
' } const About = { template: '
About
' } // 2. 定义一些路由 // 每个路由都需要映射到一个组件。 // 我们后面再讨论嵌套路由。 const routes = [ { path: '/', component: Home }, { path: '/about', component: About }, ] // 3. 创建路由实例并传递 `routes` 配置 // 你可以在这里输入更多的配置,但我们在这里 // 暂时保持简单 const router = createRouter({ // 4. 内部提供了 history 模式的实现。为了简单起见,我们在这里使用 hash 模式。 history: createWebHashHistory(), routes, // `routes: routes` 的缩写 }) // 5. 创建并挂载根实例 const app = createApp({ /* 根组件 */ }) //确保 _use_ 路由实例使 //整个应用支持路由。 app.use(router) app.mount('#app') // 现在,应用已经启动了!

3. Vuex 的使用

官方文档

安装4.0版本的Vuex

npm install vuex@next --save

示例代码

import { createApp } from 'vue'
import { createStore } from 'vuex'

// 创建一个新的 store 实例
const store = createStore({
  state () {
    return {
      count: 0
    }
  },
  mutations: {
    increment (state) {
      state.count++
    }
  }
})

const app = createApp({ /* 根组件 */ })

// 将 store 实例作为插件安装
app.use(store)
app.mount('#app')

你可能感兴趣的:(Vue3中使用vue-router、vuex)