使用Vuex、Vue路由、axios的经验汇总

博客说明:

文章所涉及的资料来自互联网整理和个人总结,意在于个人学习和经验汇总,如有什么地方侵权,请联系本人删除;如有什么地方存在异议,请在评论区或私信指出,谢谢!


一、Vuex

Vuex 是一个状态管理工具 (store是唯一的;存数据;取数据;改数据)

  1. 使用步骤

① 安装

npm i vuex --save

② 导入

import Vuex from 'vuex'

③ 使用

Vue.use(Vuex)

④ 实例化

例:

var store = new Vuex.Store({
     state:{
		n:666
    },
    mutations:{
		XXX(state,payload){
			state.n+=payload
	   }
    }
  })

⑤ 在实例中注册

new Vue({
	...
	 store,
	...
})
  1. mutations(同步改变数据)
mutaions:{
	XXX(state,payload){
		state.n+=payload
	 }
 }

注:

this.$store.commit("mutations里的方法名",参数)
  1. getters(仓库里的计算属性)
getters:{  
    属性(state){
        return 计算属性的值
     }
 }
  1. actions(异步方法)
异步方法(context,payload){
    异步成功的回调里   context.commit("mutaions里的同步方法",传参)
 }

注:

this.$store.dispatch("actions里的异步方法","参数");
  1. modules

① 分模块

var 模块={
   state:{},mutations:{},actions:{}
}

new Vuex.Store({
   modules:{
    模块的名字:引入的模块,....
   }
})

// state 有区别   this.$store.state.模块名.变量
// 其他的mutations actions,getters里的方法调用和之前一样

② 分模块后的重名问题

如果getters 重名会报错;
mutaions方法重名,各个模块的里的这个方法都会调用;
actions方法重名,各个模块里的方法都会调用;

namespaced: true, 命名空间

启用命名空间后,mutations或actions 方法名 变为 模块名/方法名

  1. 四个辅助函数
...mapState("模块名","变量"){{模块名.变量}}

...mapGetters({
 变量: 模块名/变量
})
...mapMutations({
    方法名: 模块名/mutaions里的方法名
})
...mapActions({
   方法名:模块名/actions里的方法名
})

二、Vue路由

前端路由:根据不同的url切换组件
后端路由:根据不同的请求返还不同的内容

  1. 安装
npm i vue-router —save
  1. 使用路由的步骤

① 引入vuerouter

import VueRouter from 'vue-router'

② 使用VueRouter

Vue.use(VueRouter) 

③ 实例化

var router = new VueRouter({ 
   routes:[
   		{ 
   			path:'xxx',
   			component:Com
   		}....
   ]
})

new Vue({
   ...
      router
   ...
})

⑤ App.vue中使用如下代码

<router-view />
<router-link to="/one">xxx</router-link>
  1. 路由的两种模式
    history 模式
    hash 模式
  2. 路由的重定向:redirect
  3. 命名路由:name
  4. 别名:alias
  5. 命名视图:
<router-view name="xxx" />
  {

  	path:xxx,

  	components:{

  		default:组件,  

  		router-view的名字:渲染组件;

  	}
  }
  1. 当前路由样式

router-link-exact-active

router-link-active (子路由有样式,父路由也有)

  1. 错误页面
{
   path:"**",
   component:NotFound,
}
  1. 路由传参

①传递少量参数

{
  path:'/xxx/:p',
  component:Xxx
}
this.$route.paramms.p(参数变量)

②监控参数变化

 watch:{
     $route:{
         handler(n){  n 相当于this.$route
                n.meta.flag 可以拿到路由的元数据
         },
     	immediate:true
   }
}

③ 编程式导航(适合传多个参数)

this.$router.push({name:'xxx',params:{key:value....},query:{key:vaule...}})
// 跳转到名字叫 xxx路由对象,带过去params对象里的参数,并且把query里的健值对放到 ?后面
// 拿到query 传的值  this.$route.query.变量
  1. 路由过渡效果
v-enter v-enter-active v-enter-to v-leave v-leave-active v-leave-to

<transtion mode="out-in"> out-in 是表示先退场再进场 <router-view /> </transtion>

在public/index.html 中使用从BootCDN引过来的
animate.css即可

<link href="https://cdn.bootcdn.net/ajax/libs/animate.css/3.7.2/animate.css" rel="stylesheet">
<transition mode="out-in" enter-active-class="animated slideInLeft" 
leave-active-class="animated slideOutLeft">
  1. 导航守卫
// 全局守卫
      beforeEach(to,from,next)  // to:就是切换到路由的对象; from:当前路由的对象 ;next:跳转
      afterEach(to,from)
// 路由独享的守卫
       beforeEnter
// 组件内的守卫
       // 路由进入之前
       beforeRouteEnter( 比beforeCreate要早)
       next((vm)=>{
         	vm.组件里的数据
       })
       //路由更新之前  
       beforeRouteUpdate
       //路由离开之前
       beforeRouteLeave

三、axios

  1. 安装
npm i axios --save
  1. 使用
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
axios.post('/user', {
  firstName: 'Fred',
  lastName: 'Flintstone'
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});
axios({
method: 'post',
url: '/user/12345',
data: {
 firstName: 'Fred',
 lastName: 'Flintstone'
}
}).then(function(res) {
 console.log(res)
 });
  1. 获取数据后异步传值
​ v-if 可以保证数据返回后再渲染组件
  1. axios的重复引用问题

可以在入口文件 main.js使用命令

import axios from 'axios';
Vue.prototype.$axios=axios

把请求的所有方法,都封装起来,需要请求时调用

  1. 请求中的跨域问题

1)后端:cors

res.setHeader("Access-Control-Allow-Origin","*");

2)前端:正向代理

创建vue.config.js文件

module.exports ={
devServer:{  //开发服务器设置
   proxy:{   //代理
     "/hd":{
         "target":"http://localhost:3000",
         "changeOrigin":true,
         "pathRewrite":{
             "^/hd":""
         }
     }
   }
}
}
  1. $nextTick
this.$nextTick(callback);

nextTick 延迟执行回调函数,直到dom就绪


【附】Vue中文教程

原创文章 105 获赞 1825 访问量 39万+

猜你喜欢

转载自blog.csdn.net/weixin_42881768/article/details/105874240