Vue CLI基本使用和Vue Router的概述

前言

  Vue的工具(Vue CLI)和核心插件(Vue Router)的基本指令使用。

Vue CLI

官方安装:传送门
先全局安装脚手架。

npm install -g @vue/cli
# OR
yarn global add @vue/cli

检测安装版本:vue --version或者vue -V
创建项目:vue create my-project或者vue ui使用图形化工具创建
中间根据个人配置需要内容或选项。
最后成果:在这里插入图片描述

Vue Router

官方安装:传送门
npm在已有项目中安装:npm install vue-router
路由中:

  • 默认地址比如:http://localhost:8080不写/的情况下,默认有//在url中也代表根路径。
  • {path:"/",redirect:"/home"},redirect可以重定向路由。

需要在入口man.js中配置:

import Vue from 'vue'
import App from './App.vue'
import router from "./routes/router"
new Vue({
  router,
  render: h => h(App),
}).$mount('#app')
// new Vue({
//   el:'#app',
//   router,
// })

当你把router配置到此处时,当前组件,以及后代的所有组件身上都有$route $router
并且,后代的所有的组件都可以使用<rouer-view> <router-link>

基本路由、动态路由、嵌套路由

router.js中:

// 路由相关的代码
import Vue from "vue"
import VueRouter from "vue-router"
// 一次性导入项目中的其它组件
import Home from "../components/Home"
import About from "../components/About"
// VueRouter是一个插件,在Vue中,要使用插件,必须使用Vue.use()
Vue.use(VueRouter)
// 表示路由规则
// vue中的路由:一个url对应一个组件
const routes = [
    {path:"/home",component:Home},                   基本路由
    {path:"/about/:id",component:About},             动态路由
    // {path:"/mine/:name/:age/:sex",component:Mine,meta:{address:"bj"}},
    {
        path:"/mine",                                嵌套路由
        component:Mine,
        children:[
            // { path:"/mine", redirect:"/mine/cart" },
            // { path:"/mine/cart", component:Cart },
            // { path:"/mine/member", component:Member },
            下面的写法也是OK{ path:"cart", component:Cart },//注释掉
            { path:"member", component:Member },//注释掉

            // 下面的写法也是不OK的   /表示根路径
            // { path:"/cart", component:Cart },
            // { path:"/member", component:Member },
                                                     组件的懒加载
                                                     可以在使用组件的时候再导入下方组件
            { path:"cart", component:()=>import("../components/Cart") },
            { path:"member", component:()=>import("../components/Member") },
        ]
    },
]
const router = new VueRouter({
    // mode:"hash", //默认哈希模式 url中有#
    mode:"history",//history模式 url中没有#
    routes
})

export default router;

router-link和router-view

在模板中:
router-link是一个组件,是定义好的,也是全局注册好了,可以当做a标签使用。
router-view是一个组件,是路由内置好的组件,表示路由出口

<template>
  <div id="app">
	  <h1>我是App组件</h1>
	  <hr>
	  <router-link to="/home">首页</router-link>   |   
	  <router-link to="/about">关于</router-link>
	  <!-- 路由出口 -->
	  <!-- 匹配的url,对应的组件需要放到这个出口中(坑) -->
	  <router-view></router-view>
  </div>
</template>

$route$router

在vue-router模块中,提供两个东西:

  • $route后跟属性 $route.xxx
  • $router后跟方法 $router.a()

this.$router.push会往history栈中添加一个新的记录。
route相当于当前正在跳转的路由对象。可以从里面获取name,path,params,query等。

console.log("$route:",this.$route);
console.log("$router:",this.$router);
console.log("$route:",this.$route.params.id);//这样可以拿到url中的id值

在这里插入图片描述|在这里插入图片描述

    路由:
        前端路由:vue的路由,一个url对应一个组件
        后端路由:一个url对应一个json

路由的两种模式

  vue-router默认使用的路由模式是hash模式,特点是在url后面有一个#
  除了hash路由之外,还有一种路由模式,叫history路由。url后面没有#号

  区别:

        1)history路由后面没有#    hash路由后面有#。
        2)如果你想让你的url更加规范,推荐使用history路由,history的url更加正规。
        3)history路由,很多的低版本浏览器支持性并不好,但是hash路由支持所有的浏览器,history路由的兼容性
        没有hash路由的兼容性好。
        4)如果在项目中分享第三方的app,有的app规定,你的url中不能带#,此时,你只能使用history路由。
        5)history路由 在刷新或者回车时,可能会向后端发起一个请求,如果后端不处理,就可能会出现404问题,
        如果你的项目中使用history路由,需要后端配合解决404问题。

编程式导航

当你点击<router-link> 时,这个方法会在内部调用,所以说,点击 <router-link :to="...">等同于调用 router.push(...)

在这里插入图片描述
router.push(location, onComplete?, onAbort?)
调用方式:this.$router.push

  想要导航到不同的 URL,则使用 router.push 方法。这个方法会向history 栈添加一个新的记录,所以,当用户点击浏览器后退按钮时,则回到之前的 URL

router.replace(location, onComplete?, onAbort?)
调用方式: this.$router.replace

  跟 router.push 很像,唯一的不同就是,它不会向 history 添加新记录,而是跟它的方法名一样 —— 替换掉当前的 history 记录。(所以无法返回上一步地址

router.go(n)

  这个方法的参数是一个整数,意思是在 history 记录中向前或者后退多少步,类似 window.history.go(n)。(超出历史记录个数会失败)

// 在浏览器记录中前进一步,
等同于 history.forward()
router.go(1)
// 后退一步记录,
等同于 history.back()
router.go(-1)

写在组件里面

<template>
    <div id="about">
        我是About组件
        <hr>
        <button @click="back">返回</button>
        <button @click="goAbout">去关于</button>
        <button @click="goMine">去我的</button>
    </div>
</template>

<script>
    export default{
        name:"About",
        methods:{
            back(){
                // this.$router.go(-1)
                this.$router.back();
            },
            goAbout(){
            this.$router.push("/about")
            },
            goMine(){
            // this.$router.push("mine")
            this.$router.replace("mine")
            }
        }
    }
</script>

params传参和query传参的区别?

params传参必须是name:在这里插入图片描述

url地址栏表现形式上不同:

params传参:/user/:id=>/user/123
query传参:/register?plan=private

扩展:传送门

导航守卫

官方:传送门

全局前置后置守卫

// 全局前置守卫   只要进行路由切换,肯定要拦下来
// to去哪 from来自哪 next是否放行
router.beforeEach((to, from, next) => {
    if (to.path !== "/login") {
        // 去别的路由必须登录后才行  判断是否登录
        // 如果登录了  在go上定义一个 islogin是否 true
        if (window.isLogin) {
            // 表示已登录
            next();
        } else {
            // 没有登录  return表示结束 进入登录界面
            alert("你就不能登录吗")
            return next("/login")

        }
    }
    // 放行
    next()

})
// 全局后置守卫
// 路由已进入,将要离开被拦截,拦不住,没有next不存在放行问题
router.afterEach((to,from)=>{
    if(to.path=="/home/mine"){
        alert("你真的要离开我吗呜呜呜~")
    }else{
        console.log("拜拜了~您内!")
    }
})

组件内的守卫

顾名思义:写在组件内的守卫。
此时的它和methods是同级的!!!

  methods:{},
  beforeRouteEnter(to, from, next) {
    // 在渲染该组件的对应路由被 confirm 前调用
    // 不!能!获取组件实例 `this`
    // 因为当守卫执行前,组件实例还没被创建
  },
  beforeRouteUpdate(to, from, next) {
    // 在当前路由改变,但是该组件被复用时调用
    // 举例来说,对于一个带有动态参数的路径 /foo/:id,在 /foo/1 和 /foo/2 之间跳转的时候,
    // 由于会渲染同样的 Foo 组件,因此组件实例会被复用。而这个钩子就会在这个情况下被调用。
    // 可以访问组件实例 `this`
  },
  beforeRouteLeave(to, from, next) {
    // 导航离开该组件的对应路由时调用
    // 可以访问组件实例 `this`
  }

这个离开守卫通常用来禁止用户在还未保存修改前突然离开。该导航可以通过 next(false) 来取消。

beforeRouteLeave (to, from, next) {
  const answer = window.confirm('你真的要离开吗? 你还没有保存呢!')
  if (answer) {
    next()
  } else {
    next(false)
  }
}

路由独享守卫

你可以在路由配置上直接定义 beforeEnter 守卫:

const router = new VueRouter({
  routes: [
    {
      path: '/foo',
      component: Foo,
      beforeEnter: (to, from, next) => {
        // ...
      }
    }
  ]
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值