vue-router+axios+vuex大杂烩

栏目: JavaScript · 发布时间: 6年前

内容简介:简单四步走无论/home/后面是什么,都会进入到home页面,而后面的内容会被映射成name参数获取name参数如下

简单四步走

  1. 安装
npm install --save vue-router
或者
vue add router
复制代码
  1. 引用
import router from 'vue-router'
Vue.use(router)
复制代码
  1. 配置路由文件,并在vue实例中注入
var rt = new router({//以一个对象的形式传入参数
   routes:[//数组形式,
       {
           path:'/',//指定要跳转的路径
           compoent:HelloWorld//指定要展示的组件
        //以下部分可以跳过   
           name:'helloworld'//指定该路径名称,:to="{name:“helloworld”}"//必须唯一
           children:[//嵌套路由的子路由
            {
                path:"child",// 这里不要在前面加/,
                component:() => import('./views/child.vue')//懒加载的方式
            }
           ],
           redirect:'/',//重定向
           alias:"/home";//别名,即访问“/”和“/home”跳转到同一个页面
           mode:'history';//默认为hash模式,在url上会加个#,比较难看,一般采用‘history’
       } 
   ]
})

//在vue中注入实例
new Vue({
el:"#app",
   router:rt,
   components:{App},
   template:'<App/>'
})
复制代码
  1. 确定视图加载的位置
<router-view></router-view>
复制代码

2.路由的跳转

<router-link :to="{name:'helloworld'}"></router-link>//加`:`双引号里面的是js表达式
<router-link to="/hello"></router-link>不加`:`双引号里面的是是字符串
复制代码

3.router传参数

  1. 动态路由
routes:[{
   path:"/home/:name",
   name:"home",
   component:home,
}]

<router-link :to="{name:'home',params:{name:'胡志武'}}"></router-link>
//等同
url:'http://loacalhost:8080/home/胡志武'
复制代码

无论/home/后面是什么,都会进入到home页面,而后面的内容会被映射成name参数

获取name参数如下

//在跳转的那个组件取获取
let name = this.$route.params.name;//注意$route主要用来获取参数,$router用来执行方法
复制代码
  1. get取参

    url: http://loacalhost:8080/home?name=胡志武

    获取传参: let name = this.$route.query.name

4.编程式导航

$router用来执行方法

// 字符串,这里的字符串是路径path匹配噢,不是router配置里的name
this.$router.push('/home')

// 对象
this.$router.push({ path: '/home' })

// 命名的路由 这里会变成 /user/123
this.$router.push({ name: 'user', params: { userId: 123 }})

// 带查询参数,变成 /home?name='胡志武'
this.$router.push({ path: '/home', query: { name: '胡志武' }})

// 回退到上一个历史记录
this.$router.go(-1);

this.$router.back();

//	重定向,用新的路径代替旧的历史记录
this.$router.replace('/home')
复制代码

5.命名视图

<router-view name="main"/>//这里name不是路由的name而是组件的name

//上面的视图对应下面的路由
{
	path:"/home",
	name:"home",
	components:{//注意这里是components,
		main:()=>import(‘@/home.vue’)
	}
}
复制代码

6.路由组件传参

  1. 动态路由

    路由

{
	path:'home/:name',
     component:()=>import("@/home.vue"),
     props:true,//这里要写true,表明可以传参给组件
}
     //还可以用路由编程的方法
{
    props:route=>({
        name:route.params.name
    })
}
复制代码
home组件
复制代码
// 这是没有使用路由组件传参的写法
<div>{{$route.params.name}}</div>

// 这是路由组件传参的写法
<div>{{name}}</div>

export default {
   props:{
       name:{
           type:String,
           default:'胡志武‘
       }
   }
}

复制代码
  1. 非动态路由

    路由

{
   path:'/home',
   name:'home',
   component:()=>import("@/home.vue"),
   props:{
         name:"胡志武"
    }
}

复制代码
home组件
复制代码
<div>
   {{name}}
</div>


export default{
props:{
       name:{
        type:String,
        default:'hzw'
       }
	}
}

复制代码

7.导航守卫

router.js----全局导航守卫

const LOGINED = true;//登录状态是true
//全局前置守卫。就是在真正进入另一个页面前触发
router.beforeEach((to,from,next)=>{
    //to和from都是路由对象
    //to是你即将跳转的路由对象
    //from是你即将离开的路由对象
    //next 决定路由跳转到哪里
    if(to.name!=='login'){
        //如果页面跳转的不是登录页面
        //判断其登录状态,登录了才能跳转
        if(LOGINED) next()//next(里面什么都没有则跳转到to的页面),
        else next({name:'login'})//没有登录则,跳转到登录页面
    }else{
        if(LOGINED) next({name:"home"})//已经登录了,就直接去主页
        else next();//没有登录去login页面
    }
})

//后置钩子,路由跳转成功后触发
router.afterEach((to,from)=>{
    //	这个用来关闭loding动画是最好的了
})
复制代码

路由独享守卫

{
    path:"/",
    component:home,
        //在进入这个页面前会判断
    beforeEnter:(to,from,next)=>{
    	if(from.name=='login') alert('从登录页面来')
        else alert('这不是从登录页面来的')
        
        next();//这里一定腰写next,不然路由会跳转失败
    }
}
复制代码

组件内守卫

export default{
    //在进入页面前执行,
    beforeRouterEnter(to,from,next){
		console.log(from.name);
        next();
        //这里不能直接获取组件实例
        //要获取需要使用next
        next(vm=>{
            console.log("这是组件的实例:"+vm)
        })
    },
    // 在离开页面时执行,
    afterRouterLeave(to,from,next){
        const leave = confirm('您确定要离开吗?');
        if(leave) next()//点击确定则离开
        else next(false)
    }
	// url 发生变化,并且组件复用时调用,一般是动态路由
    beforeRouterUpdate(to,from,next){
        //因为已经在页面内了,所以这里可以用this,this指向当前组件的实例
		console.log(to.name,from.name)
    }
}
复制代码

8.路由元信息

这个可以用来改变每个页面中的title属性

路由

{
    path:"/",
    component:()=>import('@/home.vue'),
    meta:{
    	title:'首页'        
    }
}
复制代码

全局导航守卫

router.beforeEach((to,from,next)=>{
    to.meta && setTitle(to.meta.title)
})

setTitle(title){
    window.document.title = title || '你好'
}
复制代码

Axios的使用

axios的简介:axios 是一个基于Promise 用于浏览器和 nodejs 的 HTTP 客户端,它本身具有以下特征:

  • 从浏览器中创建 XMLHttpRequest
  • 从 node.js 发出 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求和响应数据
  • 取消请求
  • 自动转换JSON数据
  • 客户端支持防止 CSRF/XSRF

1. 使用axios三步走

  1. 安装

    npm install axios
    复制代码
  2. 引入加载

    import axios from 'axios'
    复制代码
  3. 将axios全局挂载到VUE原型上

    这一步是为了方便全局使用

    import Vue from 'vue'
    Vue.prototype.$http = axios;
    复制代码

2.axios get请求

axios.get("/user?ID=12345")
    .then(function(res){//成功执行的函数
    	console.log(res)
	})
    .catch(function(err){//失败执行的函数
    	console.log(err);
	})
复制代码

上面的请求还可以这样子写

axios.get('/user',{
    params:{
        ID:12345
    }
})
    .then(function(res){
    	console.log(res)
	})
    .catch(function(err){
    	console.log(err);
	})
复制代码

3.axios post请求

axios.post("/user",{
    firstName:'志武',
    lastName:"胡"
})
    .then(function(res){
    	console.log(res);
	})
    .catch(function(err){
    	console.log(err)
	})
复制代码

post传递数据有两种格式:

  • form-data?page=1&limit=48
  • x-www-form-urlencoded {page:1,limit:10}

在axios中,post请求接收的参数必须是form-data

qs插件,qs.stringify

npm i -S qs

import qs from 'qs'

axios.post("/user",qs.stringify({
    firstName:'志武',
    lastName:"胡"
}))
    .then(function(res){
    	console.log(res);
	})
    .catch(function(err){
    	console.log(err)
	})
复制代码

Vuex的相关操作

vuex是用来管理状态,共享数据,在各个组件之间管理外部状态

1. 使用Vuex四步走:

  1. 引入vuex,并通过use方法使用它
import Vuex from 'vuex',
import Vue from 'vue',
Vue.use(Vuex)
复制代码
  1. 创建状态仓库
//注意Store,state不能改
var store = new Vuex.Store({
   state:{
       name:"胡志武"
   }
})
复制代码
  1. 挂载到根组件的实例上
new Vue({
    router,
    store,
    ...
})
复制代码
  1. 通过this.$store.state.name直接拿到需要的数据

2. vuex状态管理流程

view ---> actions ---> mutations ---> state ---->view

3. Vuex怎么改变状态

  1. mutations直接改变state的数据
var store = new Vuex.Store({
    state:{
        name:"胡志武"
    },
    mutations:{
    //这里传入的是state	
		change(state){
			state.name="志武胡"
		}
})


//调用
this.$store.commit('change')//这里传入的是你要调用的函数的名字
复制代码
  1. actions通过mutation来改变状态,而不是直接改变状态

    actions内部可以有异步操作,而mutations不行

var store = new Vuex.Store({
    state:{
        name:"胡志武"
    },
    mutations:{
    //这里传入的是state	
		change(state){
			state.name="志武胡"
		}
	},
    actions:{
        //这里传入的是上下文
         actionChange(context){
             context.commit('change')
          }
    }
)

//如何调用
this.$store.dispatch('actionChange')
复制代码
  1. getters 获取状态的同时,进行判断
var store = new Vuex.Store({
    state:{
        name:"胡志武"
    },
    mutations:{
    //这里传入的是state	
		change(state){
			state.name="志武胡"
		}
	},
    actions:{
        //这里传入的是上下文
         actionChange(context){
             context.commit('change')
          }
    },
    getters:{
        getName(state){
            return state.name===''?'胡志武':state.name
        }        
    
//调用
this.$store.getters.getName
)
复制代码
  1. Vuex的模块里的状态
new Vuex.Store({
    modules:{
        user:{
            state:{
                admin:'胡志武'
            },
            mutations:{},
            ...
        }
    }
})
// 如何访问
    this.$store.state.user.admin
复制代码

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Programming Python

Programming Python

Mark Lutz / O'Reilly Media / 2006-8-30 / USD 59.99

Already the industry standard for Python users, "Programming Python" from O'Reilly just got even better. This third edition has been updated to reflect current best practices and the abundance of chan......一起来看看 《Programming Python》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

在线进制转换器
在线进制转换器

各进制数互转换器

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器