vue -- fecth axios获取数据方法 路由 编程式路由 动态加载参数 hash和history模式

## keep-alive
包裹其他组件,缓存其他组件
 
1:activated
  被keep-alive组件包裹的组件,在 激活时触发
2:deactivated
  被keep-alive组件包裹的组件,在 停用时时触发
 
 
## vue中的ajax请求
 
### fetch js新增 用于请求  ajax2
  fetch(url,{
    headers:{
      "token":localStorage.getItem('token'),
      "content-type":"apllication-xxx-urlencoded"
    },
    method:"GET/POST",
    data:{
      
    }
  }).then(function(res){
    return res.json()  //text() arrayBuffer() blob() formData()
  }).then(res=>{
    //res 才是请求的结果 格式化之后(什么格式取决于 第一个 then 返回的处理方法)
  })
### axios 库  vue+axios react+axios angular+axios
1:get请求
localhost/api/v1/getArtList


axios.get('url?userName=xxx').then(res=>{}).catch(err=>)


axios.get(url,{
  params:{
    userName:"xxx"
  },
  headers:{


  }
}).then(res).catch()
2:post请求
 
 axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (res) {
    console.log(res);
  })
  .catch(function (error) {
    console.log(error);
  });
3:完整请求
axios({
  method: 'post',
  url: '/user/12345',
  headers:{


  },
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
}).then().catch()

 

 
4:创建一个 实例
可以对于 所有的请求,做一些初始化配置,配置是作用域所有的 用 实例的请求
const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

axios拦截器  拦截 请求  相应

// 添加 请求 拦截器
axios.interceptors.request.use(function (config) {
    // 可以在请求发送之前做一些事情  config 请求信息 config.headers 
    return config;
  }, function (error) {
    // 出错了 走这里
    return Promise.reject(error);
  });


// 添加相应拦截
axios.interceptors.response.use(function (response) {
    // Any status code that lie within the range of 2xx cause this function to trigger
    // 在相应数据 发送到 ajax之前,可以在这里拦截
    return response;
  }, function (error) {
    // Any status codes that falls outside the range of 2xx cause this function to trigger
    // Do something with response error
    return Promise.reject(error);
  });

 

## 路由
前端路由:根据不同的path,显示不同的组件
渐进性框架:
  1:路由功能 是以  vue 插件的形式 灌入Vue函数上 (vue.js核心包,没有路由)
  2:路由功能 单独 拿出来 vueRouter(插件的形式灌入Vue构造函数)
  3:路由 用于构建 spa (单页面应用) 应用
分析:
  优势:
  单页面应用,在我们“页面”(地址改变),不会重新加载 另一个html,只是切换路由显示。隐藏,页面切换速度以及 不同页面加载很快
  劣势:
    对于seo不友好
 (vue,ssr服务端渲染
  
[路由官网](https://router.vuejs.org/zh/)

 

## 路由实例
 
script src="vue.js" 
script  src="vue-router"


let Home = {}
let News = {}
let About = {}


const router = new VueRouter({
  routes:[
    {
      path:"/home",
      component:Home
    }
  ]
})


const vm = new Vue({
  el:"#app",
  router
})


//在el绑定 模板中  
  <router-view></router-view>   // 出口


//跳转 
 < router-link  to="/home"  tag="div"><router-link>
 
动态路由
  {
    path:"/home/:id"
  }
    <router-link  to="/home/1" >this.$route.params.id</router-link>

//默认匹配 根路径

{
  path:"/",
  component:xxx
}
//重定向
{
  path:"/",
  redirect:"/home"
},
{
  path:"/home",
  component:Home
}

//匹配404

{
  path:"*",  // * 通配符 匹配任意路由 注意 通配符放在最后
  component:NotFound
}

//监听路由 参数变化

const User = {
    template: '...',
    watch: {
      $route(to, from) {
        // 对路由变化作出响应...
      }
    }
}
 操作导航
 1:声明式
    组件 跳转
      <router-link></router-link>
2:编程式 (在js中跳转)
      1:js 路由对象提供的 方法来 跳转
      2: $router 路由 给Vue灌入一个对象,就是 路由对象(new VueRouter()),
      3:这个对象下有很多方法来操作 路由
 
this.$router.push(params); // 这个和 router-link to参数是一样的
1,字符串
      跳转路由的path
2,对象
  {
    path:"/home"
  }
  {
    name:'home'  //命名路由
  }
跳转路由并传参
1:动态路由
 
2:query传参
 
 this.$router.push({
    path:"/home",
    query:{
      a:10,
      b:20
    }
  })
  获取:
    this.$route.query.a
    this.$route.query.b
  优点:
    页面刷新 参数不丢失
  缺点:
    参数 放在url上 显式的
  注意:
    query传参 path一起使用 (最好不要和name一起使用)
 
  3:params传参 (和name是固定搭配)
 
 this.$router.push({
    name:"home",
    params:{
      a:10,
      b:20
    }
  })
  获取
    this.$route.params.a
  优点:
    隐式 (地址上不显示)
  缺点:
    刷新丢失
  注意:
    params传参和命名路由 固定搭配
 
编程式导航  replace 参数根push是一样
 
this.$router.replace()
跟 router.push 很像,唯一的不同就是,它不会向 history 添加新记录,而是跟它的方法名一样 —— 替换掉当前的 history 记录。
 
路由组件传参:{在组件中使用 $route 会使之与其对应路由形成高度耦合,从而使组件只能在某些特定的 URL 上使用,限制了其灵活性。}

 

 
*** 使用 props 将组件和路由解耦:
1,取代与 $route 的耦合:
  const User = {
  template: '<div>User {{ $route.params.id }}</div>'
}
const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User }
  ]
})

 

2,通过 props 解耦:
const User = {
  props: ['id'],
  template: '<div>User {{ id }}</div>'
}
const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User, props: true },


    // 对于包含命名视图的路由,你必须分别为每个命名视图添加 `props` 选项:
    {
      path: '/user/:id',
      components: { default: User, sidebar: Sidebar },
      props: { default: true, sidebar: false }
    }
  ]
})这样你便可以在任何地方使用该组件,使得该组件更易于重用和测试。

 

*** 布尔模式 :如果 props 被设置为 true,route.params 将会被设置为组件属性。

 

*** 对象模式 :如果 props 是一个对象,它会被按原样设置为组件属性。当 props 是静态的时候有用。
const router = new VueRouter({
  routes: [
    { path: '/promotion/from-newsletter', component: Promotion, props: { newsletterPopup: false } }
  ]
})

 

***函数模式:你可以创建一个函数返回 props。这样你便可以将参数转换成另一种类型,将静态值与基于路由的值结合等等。
const router = new VueRouter({
  routes: [
    { path: '/search', component: SearchUser, props: (route) => ({ query: route.query.q }) }
  ]
})
URL /search?q=vue 会将 {query: 'vue'} 作为属性传递给 SearchUser 组件。

 

请尽可能保持 props 函数为无状态的,因为它只会在路由发生变化时起作用。如果你需要状态来定义 props,请使用包装组件,这样 Vue 才可以对状态变化做出反应。
#对象模式
 
### 编程式导航  go
this.$router.go(n)
  n
    0  刷新
    -1 回退  
    1 前进一步

 

## 路由模式
         1:hash路由   默认的
            window.addEventListener("hashchange",(e)=>{
              // 根据hashchange 事件 来动态切换 不同组件
            })
        2: history
            路由好处:不再有#存在
            原理:
              history对象有一个 pushState
            注意:
            此模式 需要 服务器 做配置
            服务配置:
            如果 你的地址 / 重定向到 当前 index.html(有vue,vueRouter)下
 
 
一般的需求场景中,hash模式与history模式是差不多的,根据MDN的介绍,调用history.pushState()相比于直接修改hash主要有以下优势:

 

1:pushState设置的新url可以是与当前url同源的任意url,而hash只可修改#后面的部分,故只可设置与当前同文档的url
2:pushState设置的新url可以与当前url一模一样,这样也会把记录添加到栈中,而hash设置的新值必须与原来不一样才会触发记录添加到栈中
3:pushState通过stateObject可以添加任意类型的数据记录中,而hash只可添加短字符串
4:pushState可额外设置title属性供后续使用
 
## history模式的问题
 
对于单页应用来说,理想的使用场景是仅在进入应用时加载index.html,后续在的网络操作通过ajax完成,不会根据url重新请求页面,但是如果用户直接在地址栏中输入并回车,浏览器重启重新加载等特殊情况。

 

hash模式仅改变hash部分的内容,而hash部分是不会包含在http请求中的(hash带#):
 
http://oursite.com/#/user/id //如请求,只会发送http://oursite.com/
所以hash模式下遇到根据url请求页面不会有问题

 

而history模式则将url修改的就和正常请求后端的url一样(history不带#)

 

http://oursite.com/user/id
如果这种向后端发送请求的话,后端没有配置对应/user/id的get路由处理,会返回404错误。

 

官方推荐的解决办法是在服务端增加一个覆盖所有情况的候选资源:如果 URL 匹配不到任何静态资源,则应该返回同一个 index.html 页面,这个页面就是你 app 依赖的页面。同时这么做以后,服务器就不再返回 404 错误页面,因为对于所有路径都会返回 index.html 文件。为了避免这种情况,在 Vue 应用里面覆盖所有的路由情况,然后在给出一个 404 页面。或者,如果是用 Node.js 作后台,可以使用服务端的路由来匹配 URL,当没有匹配到路由的时候返回 404,从而实现 fallback。
 

 

posted @ 2020-09-02 19:16  软泥的新时代博客zu  阅读(1101)  评论(0)    收藏  举报