对于vue2的学习

系列文章目录
1 vue2入门


前言

吧啦吧啦


一、生命周期

出生 过程 死亡

2 有哪些

2.1 创建前、后

	beforeCreate
	created

2.2 挂载前、后

	beforeMount	
	mounted

2.3 修改前、后

	beforeUpdate
	updated

2.4 销毁前、后

	beforeDestroy
	destroyed

***每一个.vue文件都有以上的什么生命周期

3 生命周期使用场景

created : 请求接口
mounted : 获取dom

4 生命周期原理

class Vue{
		constructor( options ){
			options.beforeCreate();
			options.created();
		}
	}

	new Vue({
		beforeCreate(){
		   console.log('beforeCreate');
		},
	  	created(){
	       console.log('created')
	  	},
	})

5 生命周期相关

5.1 一旦进入到页面(组件)会执行哪些生命周期?

	beforeCreate
	created
	beforeMount	
	mounted

5.2 data和el在哪些阶段中有

	beforeCreate   ==>没有data和el
	created        ==>有data	没有el
	beforeMount	   ==>有data	没有el
	mounted        ==>有data和el

**** 补充
this.$ data ==> data数据
this.$ el ==> 当前组件的dom(根节点)

二、vue数据请求

三种方法

axios

代码如下(示例):

1 axios请求接口

1.1 下载

	npm install axios -S

1.2 引入

	import axios from 'axios'

1.3 使用

	axios.get()
	axios.post()
	axios({
		url:'请求url',
		method:"请求的方式",
		data:'post传值方式'
		params:'get传值方式',
	}).then(res=>{
		console.log( res );//后端给前端返回的数据
	})

2 axios二次封装 [必须会,公司一定会这样做的]

解决问题:方便管理和操作和维护:

	1. 请求的url地址统一管理
	2. 某些接口需要传递headers
//1. 引入axios
	import axios from 'axios';

	//2. 创建axios对象,url统一管理
	const service = axios.create({
		baseURL:'http://testapi.xuexiluxian.cn'
	});

	//3. 请求拦截器 ==> 前端给后端发送数据[ 没有到后端 ]
	//做的事情:headers给后端传递token
	service.interceptors.request.use(config => {
	  console.log( 1 );
	  return config;
	}, error => {
	  Promise.reject(error);
	});

	//4.响应拦截器 ==> 后端给前端返回数据[ 前端到后端了 ] ,status状态码
	service.interceptors.response.use(
	  (response) => {
	  	return response.data.data;
	  },
	  error => {
	    return Promise.reject(new Error(error.response.data))
	  }
	)
	export default service

3 api解耦

3.1 封装:

		import request from '@/utils/request'

		export function getSliders(){
			return request({
				url:'/api/slider/getSliders'
			})
		}

	3.2 使用
		
		<script type="text/javascript">
		import { getSliders } from '@/utils/api/course'
		export default{
		  data (){
		    return {
		      list:[]
		    }
		  },
		  created(){
		    getSliders().then(res=>{
		      console.log( res )
		    })
		  }
		}
		</script>  

三、vue路由

  • router
  • 单页面应用
  • SPA

单页面应用

一个url(只有一个页面)
1、跳转不同组件
2、路径传值(url传值)
3、拦截
。。。
使用
vue create </project/>
选择自定义安装:安装router
目录结构:
router/index.js ===> 路由的配置
views ===> 页面(组件)
components ===> 页面模块

veiws
	homeveiw.vue
components
	home
		Header.vue
		Swiper.vue
		Icons.vue

router-link配置

1. to : 表示目标路由的链接

	1.1 跳转形式

		  	<router-link to="/my" tag='div'>我的</router-link>
  			<router-link :to='{path:"/my"}'>新的path我的</router-link>
 			<router-link :to='{name:"Cart"}'>新的name购物车</router-link>

	1.2 路径传值 

			<router-link :to='{name:"Cart",query:{a:1}}'>新的name购物车</router-link>

2. tag

	默认生成a标签,如果希望修改 tag='li'

3. 组件形式的跳转方式

	replace
		<router-link :to="{ path: '/abc'}" replace></router-link>
	append

4、exact : 精准路由配置模式

5、通过js跳转的方式

	router.push : 打开新页面,并且可以返回上一页

		 this.$router.push('/list');

	router.replace : 打开新页面,不能返回上一页

		 this.$router.replace('/list');

	router.go   : 打开新页面,跳转几层

		this.$router.go();

	router.back : 返回上一页

		this.$router.back();

*******传值

		this.$router.push({
	        path:'/list',
	        query:{
	          type:'selectList'
	        }
	    });

文件配置

懒加载路由,一种性能优化

import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);


import Home from "../views/Home.vue";
import My from "../views/My.vue";

const routes = [
  //直接引入
  {
    path: "/home",
    name: "Home",
    component: Home,
    children:[//路由嵌套
      {
        path:'/',
        name:'/',
        component: () =>
        import("../views/Tj.vue")
      },
      {
        path:'/tj',
        name:'/tj',
        component: () =>
        import("../views/Tj.vue")
      },
      {
        path:'city',
        name:'city',
        component: () =>
        import("../views/City.vue"),
      },
      {
        path:'gz',
        name:'gz',
        component: () =>
        import("../views/Gz.vue"),
      },
      
    ]
  },
  {
    path: "/my",
    name: "My",
    component: My,
  },
  //懒加载路由
  {
    path: "/about",
    name: "About",
    component: () =>
      import("../views/About.vue"),
  },
  //重定向
  { path: '/', redirect: '/home' }
];


const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});

export default router;

路径传值

比如付款时重新选择地址

1. 传值

	this.$router.push({
        path:'/about',
        query:{
          a:1
        }
    })

2. 接收

	this.$route.query

导航守卫

拦截
登录:https://m.mi.com/address/list?type=user

没有登录:

	访问:https://m.mi.com/address/list?type=user

	跳转到了:https://m.mi.com/login

全局

不登陆,全部无法访问

	router.beforeEach((to,from,next)=>{})
	router.afterEach((to,from,next)=>{})

组件内守卫

	beforeRouteEnter((to,from,next)=>{})
	beforeRouteUpdate((to,from,next)=>{})
	beforeRouteLeave((to,from,next)=>{})

路由独享

	beforeEnter((to,from,next)=>{})


to 		:   这是你跳转到哪个路由对象
from    :   这是你要离开的路由对象
next    :   是一个方法,可以接收参数。这个方法是必须调用,如果不使用就跳转不过去,你可以把next看做一个保安,必须要跟next打个招呼你才可以通过。

	next()		==> 就是告诉保安为要过去,去哪里就是to
	next(false) ==> 可以不通过,中断跳转
	next('/')   ==> 就意思是保安不让过,你可以去另外一个地方进行通过

watch : 监听

watch ,computed ,methods

1、监听路由的变化

	watch:{
	    $route(  to,from ){
	      //to   ===> 最新的路由
	      //from ===> 上一次的路由
	      console.log( to.path , from.path );
	    }
	}

2、监听数据的变化

	watch:{

		a(to,from){
			//to   ==> 最新的
			//from ==> 上一次的
			console.log(to,from)
		}

	}

3、深度监听	

	*** 监听b但是是b的c改变了,所以要监听b内所有的属性变化,就要用到深度监听

	data () {
		return {
			b:{
			c:1
			}
		}
	}
	watch:{

		a(to,from){
			//to   ==> 最新的
			//from ==> 上一次的
			console.log(to,from)
		},
		b:{
			handler(to){
				console.log('B:',to.c)
			},
			//深度监听
			deep:true
		}

	}

四、Vuex

状态管理,集中式储存管理应用的所有组件的状态
解决问题:网购里支付选择地址,地址管理
属性	
state: {},   
getters:{},
mutations: {},
actions: {},
modules: {},

state: {}

==> 就是来放入所有数据的[类似于组件中的data]

state数据如何拿到

3.1 {{ $store.state.a }}

3.2 {{ a  }}   {{ b  }}  {{ arr }}


	<script type="text/javascript">
	import {mapState} from 'vuex'
	export default{
		computed:{
			...mapState(['a','b','arr'])
		}
	}
	</script>

getters:{},

购物车,重新计算state里的值

mutations: {},

所有对state的修改,不支持异步,通过$store.commit( ) 触发

actions: {},

定义对state的复杂修改操作,可以通过$store.dispatch( ) 触发。注意不能直接修改state,提交的是mutations,只能通过mutations 修改

modules: {},

划分state的子模块
每一个模块都有state、getters、mutations、actions,分成多个模块了

vuex 34

import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

export default new Vuex.Store({
  state: {
  	list:[  //===> length 6
  		{checked:false},
  		{checked:false},
  		{checked:false},
  		{checked:false},
  		{checked:false},
  		{checked:false}
  	],
  	selectedList:[]
  },
  getters: {
  	checkAll( state ){
  		return state.list.length == state.selectedList.length;
  	}
  },
  mutations: {
  	//全选
  	checkAll( state ){
  		state.selectedList = state.list.map(v=>{
  			v.checked = true;
  		})
  	},
  	//全不选
  	unCheckAll( state ){
  		state.list.forEach(v=>{
  			v.checked = false;
  		})
  		state.selectedList = [];
  	}
  },
  actions: {
  	checkedFn({commit,getters}){

  		getters.checkAll ? commit('unCheckAll') : commit('checkAll')

  	}
  },
  modules: {},
});

注意

1 Action 提交的是 mutation,而不是直接变更状态。
2 mutations 是同步的
	actions 可以包含任意异步操作

	**** actions更加容易调试

总结

mapState、mapGetters放在组件中的computed中

mapMutations、mapActions放在组件中的methods中

vuex持久化存储

vuex中的state可以修改吗?

1.1 

	可以:this.$store.state.xxxx
	不可以:mapState

1.2 vuex本身的mutations或actions方法的形式来修改

实习持久化存储

2.1 自己写localStorage
2.2 使用插件

	下载:npm install --save vuex-persistedstate
	使用:https://www.xuexiluxian.cn/blog/detail/dae4073b07144d3c9abb3e2cc8495922	

千万记住:Vuex就是一个放公共数据的地方,人家本身就不会一个持久化存储数据的(要做持久化存储也是可以的)。

vuex是一个状态树

目录文件管理

mutations.js mutation-type.js 文件作用

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值