引入方式变化, routes 属性加入强制判断
如果页面上没有对应的命名式路由, 如果像推送到路由上去, 原先的做法会默认导航到默认路径 (‘/’)
现在 4.x 以上版本不会有这个行为, 而是去加载一个空的组件, 且在控制台抛出异常
不会再给默认路径添加 /, redirect重定向需要写全路径
// router/index.js
// Vue2 的配置方法, 的情况下, path: '', 会在 about 前面加 /
// 比如访问 www.baodu.com/#/path 会默认转到 www.baodu.com/#/path/about
// 但是, 在 Vue3 以后就不会默认加 /
{
path: "/path",
name: "Home",
component: HomeView,
children: [
{ path: "", redirect: "about" }, // vue2 -> /path/about
{ path: "about", component: About1 },
],
}
// Vue3 的配置
// 写全路径后, 访问 www.baodu.com/#/path 会默认转到 www.baodu.com/#/path/about
// 只写 about 就只会跳到 about, 访问 www.baodu.com/#/path 会默认转到 www.baodu.com/#/about
{
path: "/path",
name: "Home",
component: HomeView,
children: [
{ path: "", redirect: "/path/about" },
{ path: "about", component: About1 },
],
}
动态路由匹配针对 (*) 需要使用 pathMatch 属性
// 当访问不到页面时, 会默认跳到 NotFount 组件
{
path: "/:pathMatch(.*)",
name: "not-found",
component: NotFound,
},
使用 createStore 方法创建 Store 实例
import { createStore } from "vuex"
export default createStore({
state: {},
getters: {},
mutations: {},
actions: {},
modules: {},
});
在 Setup 方法中使用 useStore 来引用 Store 对象
// 第一种方法
// 第二种方法
createLogger 单独抽离, 其他用法保持 Options API 一致
import { createStore, createLogger } from "vuex";
const debug = process.env.NODE_ENV !== "production";
export default createStore({
state: {},
getters: {},
mutations: {},
actions: {},
modules: {},
plugins: debug ? [createLogger()] : [],
});
Pinia
状态管理解决的问题
Vue2 中 Vuex 的使用
<!-- vuex的基本使用 -->
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
// 注册
const store = new Vuex.Store({
state: {
count: 0
},
mutaition: {
increment (state) {
state.count++
}
}
})
// 使用
store.commit('increment')
console.log(store.state.count) // -> 1
Vue3 中 Vuex 的使用
// Vue3 采用了函数式编程
import { createApp } from 'vue'
import { createStore } from 'vuex'
// 写法变化了
const store = createStore({
state () {
return {
count: 0
}
},
mutations: {
increment (state) {
state.count++
}
}
})
const app = createApp({ /* your root component */ })
// 全局注册
app.use(store)
为什么有 Pinia ?
Vue2 与 Vue3 中 Vuex 使用的变化
// store.ts
import { createStore } from "vuex";
export default createStore({
state: {
count: 0,
},
getters: {},
mutations: {
increment(state) {
state.count++;
},
decrement(state) {
state.count--;
},
},
actions: {},
modules: {},
});
count: {{ count }}
Pinia 的基本使用
// counter.ts
import { defineStore } from "pinia";
export const useCounterStore = defineStore("counter", {
state: () => ({
count: 0,
}),
actions: {
increment() {
this.count++;
},
},
});
counter: {{ counter.count }}
原生写法 (依赖注入)
定义数据和方法 (reactive) -> App.vue 主页面引入数据 (provide) -> 子组件使用数据 (inject)
// 原生使用 reactive 定义数据, 操作方法 (counter.ts)
import { reactive } from "vue";
export const useCounterOriginStore = reactive({ // 定义数据 和 方法
count: 0,
increment() {
this.count++;
},
});
CounterOrigin: {{ store.count }}
Brother: {{ store.count }}
Vuex vs Pinia vs 原生 (总结)
概念 (日常开发, 主要使用前面三个)
进阶用法
API