首页 > 其他分享 >Vue3学习(九)

Vue3学习(九)

时间:2022-11-25 08:55:40浏览次数:45  
标签:vue console log import 学习 Vue3 router name

路由学习:

1:路由传参

<template>
    <div class="cls">这是电影
        <h2>{{ $route.params.id }}</h2>
        <h2>{{ $route.params.type }} - {{ $route.params}}</h2>
        <h2>{{ $route.query }}</h2>
        <h2>{{ $route.query.name }}</h2>
        <h2>{{ $route.hash }}</h2>
        <!-- 这个要在路由中声明prop -->
        <h2>{{ id }}|{{ type }}</h2>
    </div>

</template>

<!-- 语法糖写法 -->
<!-- <script lang="ts" setup>
let props=defineProps(["id","type"])
</script> -->


<script lang="ts">
export default ({
    setup(props) {
        console.log(props)
    },
    beforeRouteEnter(to,from){
        console.log("组件内开始导航事件")
    },
    beforeRouteUpdate(to,from){
        console.log("组件内导航更新事件")
    },
    beforeRouteLeave(to,from){
        console.log("组件内导航结束事件")
    },
    props: ["id", "type"],
    created(this:any) {
        this.$watch(
            () => this.$route.params.type,
            (toParams, previousParams) => {
                console.log(toParams)
                console.log(previousParams)
            }
        )
    },
})
</script>

<style scoped>
.cls {
    background: lightskyblue;
    height: 400px;
    width: 500px;
    border: 2px solid lightblue;
    border-radius: 20px;
    padding: 20px;
    margin: 10px;
}
</style>

 

2.index.ts配置

// import home from '../view/home.vue';
import move from '../view/move.vue';
import about from '../view/about.vue';
import culture from '../view/culture.vue';
import introduce from '../view/introduce.vue';
import cart from '../view/demo_1118.vue';
import main from '../view/main.vue';
import text from '../view/text.vue';
import demo1116 from '../view/demo_1116.vue';
import axios from 'axios';
import vuex_demo1 from '../view/vuex_demo1.vue'
import { createRouter, createWebHistory, RouteRecordRaw, createWebHashHistory } from 'vue-router';
import { onBeforeMount, onMounted, onUpdated } from 'vue';

//快速定义组件
const NotFound = {
    template: '<p>没有找到您要访问的内容</p> <p>{{$route.params}}</p> <p>{{anypath}}</p>',
    props: ['anypath']
}
const home = () => import(/*webpackChunkName:"name"*/ "../view/home.vue")
let routes: RouteRecordRaw[] = [
    {
        path: "/",
        name: "home",
        // component:home
        // 重定向,跳转到/move路由下
        //redirect:"/move"
        component: home,
        meta: {
            "key": "value",  //可以自定义任意数据对象
            "requireAuth": false //是否需要验证            
        }
    },
    {
        path:"/vuex_demo1",
        name:"vuex_demo1",
        component:vuex_demo1,
        meta:{
            "requireAuth":false
        }
    },
    {
        path: "/move/:id?/:type?",//加上问好为可选参数
        name: "move",
        component: move,
        //是否允许映射到props中
        props: true,
        alias: ["/file", "/file", "/:id?(\\d+)"],
        beforeEnter: [RemoveParmes],
        meta: {
            "requireAuth": true //设置属性,是否需要验证判断
        }
    },
    {
        path: "/file",//加上问好为可选参数
        redirect: "/move",
    },
    {
        path: "/cart",
        name: "cart",
        component: cart,
    },
    {
        path: "/main",
        name: "main",
        component: main,
        meta: {
            "requireAuth": true //设置属性,是否需要验证判断
        }
    },
    {
        path: "/demo1116",
        name: "demo1116",
        component: demo1116,
        meta: {
            "requireAuth": false //设置属性,是否需要验证判断
        }
    },
    {
        path: "/text",
        name: "text",
        component: text,
        meta: {
            "requireAuth": false //设置属性,是否需要验证判断
        }
    },
    {
        path: "/login",
        name: "login",
        component: import(/*webpackChunkName:"name"*/ "../view/login.vue"),
        meta: {
            "requireAuth": true //设置属性,是否需要验证判断
        }
    },
    {
        path: "/about",
        name: "about",
        components: {
            leftView: culture,
            default: about,
            rightView: introduce
        },
        meta: {
            "requireAuth": false //设置属性,是否需要验证判断
        },
        //子路由前面不用/,要不然是从根目录开始
        //如果想打开about页面就显示第一个子路由
        //使用redirect
        redirect: "/about/culture",
        children: [{ path: "culture", component: culture }, { path: "introduce", component: introduce }]
    },
    {
        //括号外带*号:允许重复0次或1次,拿到的就是个数组
        path: "/:anypath(.*)*",
        component: NotFound,
        props: true,
        meta: {
            "requireAuth": false //设置属性,是否需要验证判断
        }
    }
];

//创建路由对象
let router = createRouter({
    //指定路由模式
    // history:createWebHashHistory(),
    history: createWebHistory(),
    routes,
    //修改路由选中的默认class(建议不改)
    // linkActiveClass:"active",
    // linkExactActiveClass:"exce"
})

let token = localStorage.getItem("token")

const $http = axios.create({
    baseURL: "http://localhost:8989/",
    timeout: 9000,
    //headers:{"token":token}
})
$http.interceptors.request.use(function (config) {
    console.log(config)
    config.headers!.token = `${localStorage.getItem('token')}`
    console.log(config)
    return config;
}, function (error) {
    return Promise.reject(error);
});




//添加导航守卫
router.beforeEach((to, from) => {
    console.log("开始导航了")
    //return true;//全部放行
    //return true;//全部阻止
    console.log("目标路径", to);
    // console.log("原始路径",from);
    //console.log(to.meta.key,to.meta.requireAuth)
    if (to.fullPath == "/main") {
        $http.post("/login/text")
            .then(response => {
                console.log("1", response.data)
                if (response.data.state == true) {
                    console.log("成功,跳转")
                } else {
                    router.push("/login")
                    alert("您的登录信息有误,请重新登录!")
                }
            })
            .catch(error => {
                return false
            })
    }
    if (to.meta.requireAuth && to.name != "login" && !authertication()) {
        return { name: "login", query: { returnUrl: to.path } }
    } else {
        return true
    }

})

//添加导航守卫
// router.beforeEach((to,from,next)=>{
//     console.log("开始导航了")
//     //next();//全部放行
//     //不带next就会全部阻止
//     if(to.name!="login"&&!authertication()){
//         next({name:"login",query:{returnUrl:to.path}});
//     }
//     next();
// })

router.afterEach((to, from) => {
    //console.log("导航后!")
})
function authertication() {
    let username = localStorage.getItem("user");
    return username;
}
//移除导航中的参数
function RemoveParmes(to, from) {
    console.log("路由独享守卫开始")
    if (Object.keys(to.params).length) {//如果有参数
        to.params = {};
        return to;
    }
    return true;
}
//移除导航中的Hash
function RemoveHash(to) {
    if (to.hash) {//如果有参数
        to.hash = {};
        return to;
    }
    return true;
}
export default router

 

3.aap.vue

<template>
    <nav>
        <router-link to="/">首页</router-link>|
        <router-link to="/move">电影</router-link>|
        <router-link to="/about">关于</router-link>|
        <router-link to="/file">重定向</router-link>|
        <router-link to="/main">后台</router-link>|
        <router-link to="/text">text</router-link>|
        <router-link to="/demo1116">demo_1116</router-link>|
        <router-link to="/cart">cart</router-link>|
        <router-link to="/vuex_demo1">vuex_demo1</router-link>|
        <div>
            <router-view name="leftView"></router-view>
            <router-view></router-view>
            <router-view name="rightView"></router-view>
        </div>

    </nav>
    <p>
        <button @click.prevent="pushHandle">router.pushi编程导航</button>
        <button @click.prevent="pushHandle2">router.go1</button>
        <button @click.prevent="pushHandle3">router.go-1</button>
    </p>
</template>

<script lang="ts" setup>
import { useRouter, useRoute } from 'vue-router'
const route = useRoute();
const router = useRouter();
function pushHandle() {
    //字符串路径
    //router.push('/about')

    //对象路径
    //router.push({path:"/move"})

    //命名的路由,并加上参数,让路由建立url
    //router.push({name:"move",params:{id:12345,type:"job"}})

    //带查询参数,结果是 /move?name=王老吉
    //router.push({name:"move",query:{name:"王老吉",price:1000}})

    // 带 hash,结果是 /about#team
    //router.push({ name: "move", hash: "#team" });

    //也可以一起带
    router.push({ name: "move", hash: "#team", params: { id: 12345, type: "job" }, query: { name: "王老吉", price: 1000 } })

    //replace相对于push,这个是修改历史记录而不是像push一样添加一条历史记录
    //router.replace("/")

}
function pushHandle2() {
    //向前移动一条记录,在历史堆栈中向前移动
    router.go(1)
}
function pushHandle3() {
    //向前移动一条记录,在历史堆栈中向前移动
    router.go(-1)
}
</script>

<style>
.active{
    background: lightblue;
    color: #fff;
}
.exce{
    background: lightgray;
    color: black;
}
</style>

 

标签:vue,console,log,import,学习,Vue3,router,name
From: https://www.cnblogs.com/zsbb/p/16924088.html

相关文章

  • 驱动开发学习笔记---字符设备
    字符设备是按照字节流进行读写操作的设备,读写数据是分先后顺序的。常见的点灯、按键、IIC、SPI和LCD等都是字符设备。字符设备驱动开发步骤:总体思路:------定义并初......
  • 学习《Python编程 从入门到实践》第二、三天
    近期比较忙,宝宝的预产期是12月17日,老婆每天都跟我说准备要生了。所以昨天看了一会就做家务活了,练习完后忘记写日记了。今天给补上。 为什么突然想学编程呢?其实是平常......
  • vue3中watch监听不是你想的那样简单
    vue3中watch监听数组,数组变化后未触发回调今天发生了一个很神奇的现象,就是我使用watch监听数组时。被监听的数组已经发生了变化。但是没有触发回调操作。当时的我感到......
  • 学习python-Day92
    requests高级用法https和http的区别https=http+ssl或者tsl(ssl或tsl是加密的证书)注意:没有认证的机构就是没有签发证书,访问的时候,浏览器会提示不安全的。ssl认证......
  • C++学习笔记——static
    //#include<iostream>//usingnamespacestd;////classTen//{//private://staticintc;//当静态成员函数在私有成员下定义,类外不可对其进行访问......
  • Python爬虫学习-cnblog
    Python爬虫学习Python的文件操作序列化与反序列化通过文件操作,我们可以将字符串写入到一个本地文件。但是如果是一个对象(列表、字典、元组等),就无法直接写入到一个文件中......
  • C++学习笔记——友元函数
    //#include<iostream>//usingnamespacestd;////classStu//{//protected://private://intage;//voidfun()//{//age=12;//......
  • C++学习笔记——构造函数
    //#include<iostream>//usingnamespacestd;////classStu//{//public://intage;//floatf;////构造函数,可由系统自动调用//Stu()//......
  • C++学习笔记——析构函数
    //#include<iostream>//usingnamespacestd;////classFive//{//public://intn;//Five()//定义一个构造函数//{//cout<<"调用......
  • C++学习笔记——带参构造函数
    //#include<iostream>//usingnamespacestd;////classStu//{//public://intage;//floatf;////构造函数,可由系统自动调用//Stu()//......