promise介绍+vuex模块化开发

196 阅读1分钟

1.axios实例就是promise对象
2.如何声明一个promise

 new Promise(function(resolve,reject){
  resolve('success') //成功执行  reject('fail') //失败执行reject
 }).then(result=>{
   alert(result)
 }).catch(error=>{
    alert(error)
 })

3.vuex模块化开发

 import axios from 'axios'
 module.exports={
  state:{
   // 存储token
   token:'',
   // 存储用户信息
   userInfo:{}
  },
  // 唯一同步更新数据地方
  mutations:{
  // 定义更新token函数
  updateToken(state,newToken){
   state.token=newToken
  },
   // 定义更新userInfo的函数
   updateUserInfo(state,info){
    state.userInfo=info
   }
  },
  // 实现异步更新的地方
  actions:{
  // context:Store仓库的实例对象
  async ininUserInfo(context){
    console.log(context,'ininUserInfo')
    // 发送请求,获取数据
    const {data:res} = await axios.get('/my/userinfo')
    console.log(res)
    // 3.调用mutations中的函数,传递数据,进行保存
    if(res.code===0){
     context.commit('updataUerInfo',res.data)
    }
   }
  }
 }

4.getters在vuex中的使用

// 建立快捷访问的方式
getters:{
  user_pic:state => state.user.userInfo.user_pic
}

// 在使用时:
// <img :src="userInfo.user_pic" v-if="$store.state.user.userInfo.user_pic">
// 简写成:
 <img :src="userInfo.user_pic" v-if="$store.getters.user_pic">

image.png

5.使用路由导航守卫控制访问权限
(1)登陆用户不能再次回到login
(2)没有登陆就不能访问除login之外的其它页

image.png

// 添加路由守卫
// beforeEach() 路由跳转之前一定会经过这里
router.beforeEach(to,from,next)=>{
 console.log('要去哪里',to)
 console.log('从哪里来',from)
 // next() 放行 || next('路径') 指定路径跳转到指定的页面
 next()
}

// 判断是否有token

router.beforeEach((to,from,next)=>{
 const token=store.state.user.token
 if(token){ // 有token
  if(to.path==='/login'){
    console.log('您已经登陆,不能去登录页,直接跳转到首页')
    router.push('/')
   }else{
    // 没有token
    // 判断是否是白名单:不需要权限 ----> /login   /reg
    // 首页需要权限,去不了,但是页面和页面之前的跳转不需要,
    if(to.path==='/login' || to.path==='/reg'){ 
      next()
    }else{
     console.log('没有白名单,跳转到登录页')
     router.push('/login')
    }
   }
 }
})

6.路由懒加载
问题:在进入主页的时候就加载了所有的信息,
预期:应该在点击到某个页面的时候才加载
可以提高网页打开的速度
(1)需要先下载安装babel插件 image.png

image.png

实现:

image.png image.png