Vue路由
重定向 redirect
作用:自定义网页打开的默认页面 语法:
import NotFound from "../views/not-found.vue";
routes: [
// 写在routes最上面
{
path: "/",
// redirect:设置要重定向到哪个路由路径
redirect: "/page1",
},
],
404
作用:当找不到路径匹配时,给个提示页面 注意:一定要放在最后一项,当前面的都匹配不到才会匹配最后
// 对应页面需要自己写,需要引用
import NotFound from "../views/not-found.vue";
routes: [
// 写在最后面
{
path: "*",
component: NotFound,
},
],
模式设置
作用:修改路由在地址栏的模式 hash路由,例: http://localhost:8080/#/home history路由,例: http://localhost:8080/home (以后上线需要服务器端支持) 语法:
const router = new VueRouter({
routes,
// 写在routes之外
mode: "history",
});
编程式导航
基本跳转
定义:给任意标签添加JS代码,来进行页面跳转 语法:
<template>
<div>
<button @click="$router.push({ path: '/page1', query: { name: 'page1', age: 18 } })">编程式导航页面1</button>
<button @click="$router.push(`/page2/${id}`)">编程式导航页面2</button>
<router-view></router-view>
</div>
</template>
缺点:在当前页面时,再次点击对应标签会报错
路由传参
和声明式导航一致
过滤器
vue2中使用,method能实现所有的功能,vue3已弃用
<template>
<div>
<h6>{{ "iron man" | upper }}</h6>
</div>
</template>
<script>
export default {
filters: {
upper(value) {
return value.toUpperCase();
},
},
};
</script>
Vuex 3.x
理解:简单来说,是数据管理仓库,Vue中的数据都叫状态,是借鉴React思想的。 作用:解决父传子子传父的混乱数据,统一把数据搬到仓库,
仓库搭建
步骤(类似路由器)
- 下载Vuex模块到当前工程,版本3.x
- Vue2使用3.x版本,Vue3使用4.x版本
npm i Vuex@3
- 在index.js中引入vue和vuex函数
import Vue from "vue";import Vuex from "vuex";
- 添加到Vue.use()身上
- 在main.js中配置
Vue.use(Vuex);
- 在main.js中配置
- 创建仓库对象
const store = new Vuex.Store({
state: { // 类似vue中的data
count: 1000,
},
mutations: { // 类似vue中的methods
increment(state, payload) {
state.count -= payload.num;
},
},
});
- 输出
export default store; - 在main.js中引入store
import store from "./store";
- 路由对象注入到new Vue实例中
- 在 new Vue({ })中添加
store: store,
- 在 new Vue({ })中添加
案例
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const store = new Vuex.Store({
state: { // 类似vue中的data
count: 1000,
},
mutations: { // 类似vue中的methods
increment(state, payload) {
state.count -= payload.num;
},
},
});
export default store;
// 在main.js中配置
import store from "./router/store";
new Vue({
// 8.将仓库对象注入到new Vue实例中
store,
render: (h) => h(App),
}).$mount("#app");
仓库使用
- 调用数据:写在computed中
<script>
export default {
computed: {
return this.$store.state.变量;
},
},
</script>
- 调用函数:
- 避免在组件中修改数据,需要把通知仓库修改数据
<script>
export default {
methods: {
add() {
//increment 是仓库中mutations声明的函数
this.$store.commit("函数名", 传参);
},
},
};
</script>
案例
<template>
<div>
<h1>count: {{ count }}</h1>
<button @click="add">-7</button>
</div>
</template>
<script>
export default {
computed: {
count() {
return this.$store.state.count;
},
},
methods: {
add() {
//increment 是仓库中mutations声明的函数
this.$store.commit("increment", { num: 7 });
},
},
};
</script>