vue-cli3 -路由

  • babel 作用:es6转es5
  • eslint:代码规范
  • git add . 添加
  • git commit -m ‘注释’ (将之前add的内容添加本地仓库里面)
  • git push (提交到远程仓库)
  • npm install 会根据package.json下载npm包
  • 定义函数:
// 对象字面量中定义函数
const obj = {
  aaa(){},
  bbb:function(){},
}
// 箭头函数
// const ccc = (参数列表) =>{}
//没有参数
const ccc = () =>{}

// 一个参数,括号可以省略
const power = num =>{
  return num * num;
}
//函数代码块中有多行代码时:
const test = () => {
  console.log('hello world');
  console.log('vue.js');
}

// const mul = (num1,num2) => {
//   return num1 * num2;
// }
//只有一行代码时,不用写return
const mul = (num1,num2) => num1 * num2;
  • 箭头函数中的this向外层作用域中,一层层查找this,知道有this的定义
 <script>

    // setTimeout(function(){
    //   console.log(this); //window
    // },2000);

    // setTimeout(() =>{
    //   console.log(this);   //window
    // },2000)

    //结论:箭头函数中的this引用的就是最近作用域的this,不像其他函数是call
    // const obj = {
    //   aa(){
    //     setTimeout(function(){
    //       console.log(this); //window
    //     });
    //     console.log(this) //obj对象
    //     setTimeout(() => console.log(this)); //obj对象
    //   }
    // }
 
    const obj = {
      aa(){
        setTimeout(function(){
          setTimeout(function(){console.log(this); }); //window
          // this == window (window调用了setTimeout)
          setTimeout(() => console.log(this)); //window
        });
        
        setTimeout(() => {
          setTimeout(function(){console.log(this); });//window
          setTimeout(() => console.log(this)); //obj
        }); 
      }
    }
    obj.aa()
  
    
  </script>
  • 路由表: 映射表,决定了数据包的指向

  • 改变href但是页面不发生刷新的方法:
    1.通过改变location.hash
    2.history.pushState({},’’,‘home’);

  • history.back() 出栈(相当于浏览器返回)

  • history.replaceState({},’’,‘about’) 会覆盖之前的,不会保存记录

  • history.go(-2); 弹出两个 history.go(3),入栈3个

  • history.go(-1) 等价于history.back()

  • history.forward(); history.go(1)

  • vue-router 是基于路由和组件的
    1.路由用于设定访问路径,将路径和组件映射起来
    2.在vue-router的单页面应用中,页面的路径的改变就是组件的切换

  • 使用vue-router
    1.首先需要先安装vue-router npm install vue-router --save
    2.在router新建index.js

import VueRouter from 'vue-router'
import Vue from 'vue'
import Home from "../components/Home"
import About from "../components/About"
// 因为它是一个插件,所以可以通过Vue.use()来安装路由功能
Vue.use(VueRouter)

const routes = [
  {
    path:'/home',
    component:Home,
  },
  {
    path:'/about',
    component:About,
  }
]
//创建路由实例
const router = new VueRouter({
  //配置路由和组件的映射关系
  routes, //相当于routes:routes
});

//导出路由给index使用
export default router 
//然后在main.js 挂载这个router实例
import Vue from 'vue'
import App from './App.vue' //导入App.vue组件
import router from './router' //自动去找这个文件夹里的index.js,所以index可以省略不写
Vue.config.productionTip = false

new Vue({
  router, //挂载路由

  //渲染App.vue内容
  render: h => h(App)
}).$mount('#app') //相当于:el:'#app'

3 . 使用路由:
在App.vue中

<template>
  <div id="app">
    <router-link to="/home">首页</router-link>
    <router-link to="/about">关于</router-link>
    <router-view></router-view>
  </div>
</template>
<script>
export default {
  name:'App'
}
</script>
<style>
</style>

  • 路由的默认路径,在routes里面添加
	{
    path:'/',
    redirect:'/home',
  },
  • 更改路由的模式为history,默认为hash
const router = new VueRouter({
  //配置路由和组件的映射关系
  routes,
  mode:'history'
});
  • 加上replace,调用的就是history.replace 而不是history.pushState(),这样就不能使用前进后退功能
<router-link to="/home" tag="button" replace>首页</router-link>
    <router-link to="/about" tag="button" replace>关于</router-link>
  • 通过代码跳转路由
<template>
  <div id="app">
    <!-- <router-link to="/home" tag="button" replace>首页</router-link>
    <router-link to="/about" tag="button" replace>关于</router-link> -->
    <button @click="homeClick">首页</button>
    <button @click="aboutClick">关于</button>
    <router-view></router-view>
  </div>
</template>
<script>
export default {
  name:'App',
  methods:{
    homeClick(){
    // 这里的$.router是router/index.js里面的router
      // this.$router.push("/home")
      //没有前进后退,使用replace
      this.$router.replace("/home")
    },
    aboutClick(){
      //  this.$router.push("/about")
      this.$router.replace("/about")
    }
  }
}
</script>
<style>
.router-link-active{
  color:red
}

</style>

  • 动态路由
// router/index.js文件
{
   path:'/user/:abc',
   component:User,
  }
// App.vue

//注意:属性获取值用的是v-bind
<router-link v-bind:to="'/user/'+userId" tag="button" replace>用户</router-link>

export default {
  name:'App',
  data(){
    return{
      userId:'lisi'
    }
  },

User.vue

<template>
  <div>
    <h2>我是用户界面</h2>
    <p>嗨嗨嗨</p>
    <h3>{{userId}}</h3>
    <!-- 或者使用下面这种方式,注意不用加this,因为$route相当于data(){return{ $route,}}; 在template获取data里面的值不用加this -->
    <h3>{{$route.params.abc}}</h3>
  </div>
</template>

<script>
export default{
  name:'User',
  computed:{
    userId(){
      return this.$route.params.abc //这里的userId是 path:'/user/:abc' 里面的abc;$route指向活跃的那个路由
    }
  }
}
</script>

<style>

</style>
  • 懒加载:将路由对应组件打包成一个个的js代码块。
    访问该路由时再加载对应组件
// 懒加载
const Home = () => import('../components/Home')
const About = () => import('../components/About')
const User = () => import('../components/User')
  • 路由的嵌套
// router/index.js
const HomeNews = () => import('../components/HomeNews')
const HomeMessage = () => import('../components/HomeMessage')

const routes = [
  {
    path:'/',
    redirect:'/home',
  },  
  {
    path:'/home',
    component:Home,
    children:[
      {
        path:'',
        redirect:'news' //访问/home重定向到/home/news
      },
      {
        path:'news', //注意前面不用加'/'
        component:HomeNews,
      },
      {
        path:'message',
        component:HomeMessage,
      }
    ]
  },

// Home.vue
<template>
  <div>
    <h2>我是首页</h2>
    <p>我是首页内容,hahaha</p>
    <!-- 前面要加'/' -->
    <router-link to="/home/news">新闻</router-link>
    <router-link to="/home/message">消息</router-link>
    <router-view></router-view>
  </div>
</template>
  • 传递参数主要有两种类型:params和query
    params的类型
    配置路由格式:/router/:id
    query 的类型
 <router-link :to="{path:'/profile',query:{name:'zjh',age:14,sex:'male'}}" 
    tag="button" replace>档案</router-link>
    <!--访问该路由时,浏览器的url显示: http://localhost:8080/profile?name=zjh&age=14&sex=male -->
 
 //Profile.vue
 <template>
  <div id="ppp">
    <h3>我是profile组件</h3>
    //取出参数
    <h3>{{$route.query.name}}</h3>
    <h3>{{$route.query.age}}</h3>
    <h3>{{$route.query.sex}}</h3>
  </div>
</template>

```javascript
<!-- <router-link to="/profile" tag="button" replace>档案</router-link> -->
    <!-- 与上面的作用相同,注意是v-bind:to ,否则"{path:'/profile'}"会被当成字符串,而不是对象 -->
    <router-link :to="{path:'/profile'}" tag="button" replace>档案</router-link>
	//App.vue
	<button @click="userClick">用户</button>
    <button @click="profileClick">档案</button>
	userClick(){
      this.$router.replace("/user/"+this.userId);
    },
    profileClick(){
      this.$router.replace({
        path:'/profile',
        query:{
          name:'kobe',
          age:19,
          height:1.88
        }
      })
    },
  • $ route 活跃的(浏览器地址)那个路由;为当前router跳转的对象,里面可以获取name,path,query,params等
    -$ router 为VueRouter实例,想要导航到不同URL,则使用$router.push或者replace方法
  • created() 组件创建是调用该方法
  • mounted() 组件的template挂载到DOM 上时调用
  • updated() 界面发生刷新是调用该方法
  • 路由导航守卫:(全局守卫)
    vue- router提供的导航守卫主要用来监听路由的进入和离开
    vue -router提供了beforeEach 和afterEach的钩子函数,他们会在路由即将改变前和改变后触发
    导航钩子(beforeEach)的三个参数解析:
    1.to: 即将要进入的目标的路由对象
    2.from: 当前导航即将要离开的路由对象
    3.next: 调用该方法后,才能进入下一个钩子
    补充:如果是后置钩子,也就是afterEach,不需要主动调用next()函数,因为已经跳转完了
router.afterEach((to,from) =>{
  console.log('----');
})
  • 案例:改变组件时改变titile
//index.js
router.beforeEach((to,from,next) =>{
  document.title = to.matched[0].meta.title;
  console.log(to);
  next()
})

{
  path:'/about',
   component:About,
   meta:{
     title:'关于',
   },
},
  • 路由独享守卫beforeEnter
{
   path:'/profile',
   component:Profile,
   meta:{
     title:'档案',
   },
   beforeEnter:(to,from,next) =>{
     console.log('profile beforeEnter');
     next()
   }
 }
  • 组件内的守卫
  • keep-alive是Vue内置的一个组件,可以是被包含的组件保留状态,或避免重新渲染
    1,include :字符串或者正则表达式,只有匹配的组件才需要缓存
    2,exclude : 排除在外,当组件变化需要销毁和重新创建
//exclude是组件的name
<keep-alive exclude="Profile,User">
      <router-view></router-view>
    </keep-alive>
  • router-view 也是一个组件,如果直接被包在keep-alive里面,所有路径匹配到的视图组件都会被缓存
  • Vue组件activated() 组件活跃的时候调用 deactivated() 组件不活跃的时候调用,前提是这个组件所在的router-view有被keep-alive 包着,才有效
  • this.$route.path 获取路由路径 this. $ router.push() 或者replace()改变路由路径
//在离开组件的时候记录他的path
beforeRouteLeave(to,from,next){
    this.path = this.$route.path;
    next()
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值