前端入门之VUE--ajax、vuex、router,最后的前端总结

前言

  • VUE是前端用的最多的框架;
  • 这篇文章是本人大一上学习前端的笔记;
  • 欢迎点赞 + 收藏 + 关注,本人将会持续更新。
  • 本人不是学前端的,这个是大一的时候上学的和做的笔记,那个时候学的也蒙,故这里对前端做一个总结

文章目录

4、Vue中的Ajax

4.1、Vue脚手架配置代理

下载axios库:npm install axios

vue脚手架配置代理服务器:

  • 方法一:在vue.config.js中添加如下配置

    js 复制代码
    devServer: {
        proxy: "http://localhost:5000"
    }

    说明:

    1. 优点:配置简单,请求资源时直接发给前端即可
    2. 缺点:不能配置多个代理,不能灵活的控制请求是否走代理
    3. 工作方式:若按照上述配置代理,当请求了前端不存在的资源时,那么该请求会转发给服务器 (优先匹配前端资源)
  • 方法二:

    js 复制代码
    devServer: {
        proxy: {
          	'/api1': { // 匹配所有以 '/api1'开头的请求路径
            	target: 'http://localhost:5000',// 代理目标的基础路径
            	changeOrigin: true,
            	pathRewrite: {'^/api1': ''}
          	},
          	'/api2': { // 匹配所有以 '/api2'开头的请求路径
            	target: 'http://localhost:5001',// 代理目标的基础路径
            	changeOrigin: true,
            	pathRewrite: {'^/api2': ''}
          	}
        }
    }
    
    // changeOrigin设置为true时,服务器收到的请求头中的host为:localhost:5000
    // changeOrigin设置为false时,服务器收到的请求头中的host为:localhost:8080

    优点:可以配置多个代理,且可以灵活的控制请求是否走代理

    缺点:配置略微繁琐,请求资源时必须加前缀

4.2、vue-resource

下载 vue-resource库:npm i vue-resource

总结:

vue项目常用的两个Ajax库:

  1. axios:通用的Ajax请求库,官方推荐,效率高
  2. vue-resource:vue插件库,vue 1.x使用广泛,官方已不维护
4.3、slot插槽

作用:让父组件可以向子组件指定位置插入html结构,也是一种组件间通信方式

分类:默认插槽、具名插槽、作用域插槽

使用方法:

  1. 默认插槽

    vue 复制代码
    父组件中:
    		<Category>
                <div>html结构1</div>
    		</Category>
    子组件中:
    		<template>
    			<div>
                    <slot>插槽默认内容</slot>
                </div>
    		</template>
  2. 具名插槽

    vue 复制代码
    父组件中:
    	<Category>
            <template slot="center">
    			<div>html 1</div>
            </template>
            
            <template v-solt:footer>
    			<div>html 2</div>
            </template>
    	</Category>
    子组件中:
    	<template>
    		<solt name="center">默认卡槽内容</solt>
    		<solt name="footer">卡槽默认内容</solt>
    	</template>
  3. 作用域插槽

vue 复制代码
父组件中:
		<Category>
			<template scope="scopeData">
				<!-- 生成的是ul列表 -->
				<ul>
					<li v-for="g in scopeData.games" :key="g">{{g}}</li>
				</ul>
			</template>
		</Category>

		<Category>
			<template slot-scope="scopeData">
				<!-- 生成的是h4标题 -->
				<h4 v-for="g in scopeData.games" :key="g">{{g}}</h4>
			</template>
		</Category>
子组件中:
        <template>
            <div>
                <slot :games="games"></slot>
            </div>
        </template>
		
        <script>
            export default {
                name:'Category',
                props:['title'],
                //数据在子组件自身
                data() {
                    return {
                        games:['红色警戒','穿越火线','劲舞团','超级玛丽']
                    }
                },
            }
        </script>

5.Vuex插件

5.1、理解vuex
5.1.1、Vuex是什么
  1. 概念:专门在 Vue 中实现集中式状态(数据)管理的一个 Vue 插件,对 vue 应用中多个组件的共享状态进行集中式的管理(读/写),也是一种组件间通信的方式,且适用于任意组件间通信
5.1.2、什么时候用vue
  1. 多个组件依赖同一个状态
  2. 来自不同组件的行为需要变更同一状态
5.2搭载Vuex环境
  1. 下载Vuex:npm i vuex
  2. 创建src/store/index.js
js 复制代码
//引入Vue核心库
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用Vuex插件
Vue.use(Vuex)

//准备action对象响应组件中用户的动作、处理业务逻辑
const active ={}
//准备mutations对象------修改state中的数据
const mutations = {}
//准备state对象------保存具体的数据
const state = {}

//创建并暴露store
export default new Vuex.Store({
    actions,
    mutations,
    state
})

src/main.js中创建 vm 时传入store配置项:

vue 复制代码
import Vue from 'vue'
import App from './App.vue'
import Vuex from 'vuex'
import store from './store'

Vue.config.productionTip = false

Vue.use(Vuex)

new Vue({
    el:"#app",
    render: h => h(App),
    store
})
5.2.1、使用Vuex编写

src/components/Count.vue:

vue 复制代码
<template>
	<div>
        <h1>当前求和为:{{$store.state.sum}}</h1>
        <select v-model.number="n">
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            
    	</select>
        <button @click="increment">+</button>
        <button @click="decrement">-</button>
        <button @click="incrementOdd">当前求和为奇数再加</button>
        <button @click="incrementWait">等一等再加</button>
        
    </div>
</template>

<script>
    export default {
        name: 'Count',
        data() {
            return {
                n: 1,
            }
        },
        methods: {
            increment() {
                this.$store.commit('ADD',this.n)
            },
            decrement() {
                this.$store.commit('SUBTRACT',this.n)
            },
            increamOdd() {
                this.$store.dispatch('addOdd',this.n)
            },
            incrementWait()  {
                this.$store.dispatch('addWait',this.n)
            }
        }
    }
</script>

src/store/index.js:

vue 复制代码
//引入vue核心库
import Vue from 'vue'
//引入Vuex
import Vuex from 'vuex'
//应用vuex插件
Vue.use(Vuex)

//准备一个action对象
const active = {
	addOdd(context,value) {
	console.log("actions中的addOdd被调用了")
	if(context.state.sum%2){
		context.commit('ADD',value)
		}
	},
	addWait(context,value) {
		console.log("actions中addWait被调用了")
		setTimeout(() => {
			context.commit('ADD',value)
		},500)
	}
},
//准备mutations对象------修改state中的数据
const mutations = {
	ADD(state,value) {
		state.sum += value
	},
	SUBTRACT(state,value) {
		state.sum -= value
}
},
//准备state对象------保存具体的数据
const state = {
	sum: 0
}

//创建并且暴露store
export default new Vuex.Store({
	actions,
	mutations,
	state
})

总结:

Vuex的基本使用:

1.初始化数据state,配置actionsmutations,操作文件store.js

js 复制代码
//引入Vue核心库
import vue from 'vue'
//引入VUex
import vuex from 'vuex'
//引入Vuex
Vue.use(Vuex)

const action = {
	//响应式添加动作
	jia(context,value) {
        context.commit('JIA',value)
    },
}

const mutations = {
    //执行加
    jia(state,value) {
     	state.sum += value
    }
}

const state = {
    sum:0
}

//创建并暴露store
export default Vuex.store({
    actions,
    mutations,
    state,
})
  • 组件中读取vuex中的数据:$store.state.sum
  • 组件中修改vuex中的数据:$store.dispatch('action中的方法名',数据)$store.commit('mutations中的方法名',数据)
5.3、getters配置项

总结:

getters配置项的使用:

  1. 概念:当state中的数据需要经过加工后再使用时,可以使用getters加工
  2. store.js中追加getters配置
js 复制代码
...
const getters = {
	bigSum(state){
		return state.sum * 10
	}
}

//创建并暴露store
export default new Vuex.Store({
	...
	getters
})

​ 3.组件中读取数据:$store.getters.bigSum

5.4、四种方法
  1. mapState方法:用于帮助我们映射state中的数据

    vue 复制代码
    computed: {
        //借助mapState生成计算属性:sum、school、subject(对象写法)
         ...mapState({sum:'sum',school:'school',subject:'subject'}),
             
        //借助mapState生成计算属性:sum、school、subject(数组写法)
        ...mapState(['sum','school','subject']),
    },
  2. mapGetters方法:用于帮助我们映射getters中的数据

    vue 复制代码
    computed: {
        //借助mapGetters生成计算属性:bigSum(对象写法)
        ...mapGetters({bigSum:'bigSum'}),
    
        //借助mapGetters生成计算属性:bigSum(数组写法)
        ...mapGetters(['bigSum'])
    },
  3. mapActions方法:用于帮助我们生成与actions对话的方法,即:包含$store.dispatch(xxx)的函数

    vue 复制代码
    methods:{
        //靠mapActions生成:incrementOdd、incrementWait(对象形式)
        ...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
    
        //靠mapActions生成:incrementOdd、incrementWait(数组形式)
        ...mapActions(['jiaOdd','jiaWait'])
    }
  4. mapMutations方法:用于帮助我们生成与mutations对话的方法,即:包含$store.commit(xxx)的函数

    vue 复制代码
    methods:{
        //靠mapActions生成:increment、decrement(对象形式)
        ...mapMutations({increment:'JIA',decrement:'JIAN'}),
        
        //靠mapMutations生成:JIA、JIAN(对象形式)
        ...mapMutations(['JIA','JIAN']),
    }
5.5、模块化 + 命名空间
  1. 目的:让代码更好维护,让多种数据分类更加明确

  2. 修改store.js

    js 复制代码
    const countAbout = {
        namespace: true,  //开启命名空间
        state: {x:1},
        mutation: {...},
        actions: {...},
        getters: {
            bigSum(state) {
                return state.sum * 10
            }
        }
    }
    
    const personAbout = {
            namespace: true,
            state: {...},
        	mutations: {...},
            actions: {...}
    }
                        
    const store = new Vuex.store({
        modules: {
        	countAbout,
        	personAboutx
    }
    })
  3. 开启命名空间,组件中读取state数据

    js 复制代码
    //1.直接读取
    this.$store.personAbout.list
    //2.借助mapState读取
    ...mapState('countAbout',['sum','school','subject']),
  4. 开启命名空间后,组件中读取getters数据:

    js 复制代码
    //1.自己直接读取
    this.$store.getter['personAbout/firstPersonName']
    //2.借助mapgetters读取
    ...mapGetters('sountAbount',['bigSum'])
  5. 开启命名空间后,组件中调用dispatch:

    js 复制代码
    //方式一:自己直接dispatch
    this.$store.dispatch('personAbout/addPersonWang',person)
    //方式二:借助mapActions:
    ...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
  6. 开启命名空间后,组件中调用commit:

    js 复制代码
    //方式一:自己直接commit
    this.$store.commit('personAbout/ADD_PERSON',person)
    //方式二:借助mapMutations:
    ...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),

6.Vue Router路由管理器

6.1、相关理解
  • vue 的一个插件库,专门用来实现SPA 应用
    • 整个页面只有一个完整的页面
    • 点击页面的导航链接不会刷新页面,只会局部更新
6.2、基本路由
  1. 安装vue-router,命令:npm i vue-router

  2. 应用插件Vue.use(VueRouter)

  3. 编写router配置项:

    vue 复制代码
    //引入VueRouter
    import VueRouter from 'vue-router'
    //引入Luyou 组件
    import About from '../components/About'
    import Home from '../components/Home'
    
    //创建router实例对象,去管理一组一组的路由规则
    const router = new VueRouter({
    	routes:[
    		{
    			path:'/about',
    			component:About
    		},
    		{
    			path:'/home',
    			component:Home
    		}
    	]
    })
    
    //暴露router
    export default router
  4. 实现切换(active-class可配置高亮度样式)

    html 复制代码
    <router-link active-class="active" to="/about">About</router-link>
  5. 指定展示位:

src/router/index.js:

js 复制代码
//该文件专门用于创建整个路由
import VueRouter from "vue-router"
//引入组件
import Home from ''
import About from ''

//创建并且暴露一个路由
export default new VueRouter({
    routes: [
        {
            path: '/about'
            component: About
        },
        {
            path: '/home'
            component: Home
        }
    ]
})

src/main.js:

vue 复制代码
import Vue from 'vue'
import App from  './App.vue'
import VueRouter from 'vue-router'
import router from './router'

Vue.use(VueRouter)

new Vue({
	el:'#root',
	render: h => h(App)
	router
})

src/App.vue:

vue 复制代码
<template>
	<div>
		<div class="row">
			<div class="col-xs-offset-2 col-xs-8">
				<div class="page-header"><h2>Vue Router Demo</h2></div>
			</div>
		</div>
		<div class="row">
			<div class="col-xs-2 col-xs-offset-2">
				<div class="list-group">
					<!-- 原始html中我们使用a标签实现页面跳转 -->
					<!-- <a class="list-group-item active" href="./about.html">About</a>
					<a class="list-group-item" href="./home.html">Home</a> -->
					
					<!-- Vue中借助router-link标签实现路由的切换 -->
					<router-link class="list-group-item" active-class="active" to="/about"> 							About
    				</router-link>
					<router-link class="list-group-item" active-class="active" to="/home">
                        Home
    				</router-link>
				</div>
			</div>
			<div class="col-xs-6">
				<div class="panel">
					<div class="panel-body">
						<!-- 指定组件的呈现位置 -->
						<router-view></router-view>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	export default {
		name:'App',
	}
</script>

src/components/Home.vue:

vue 复制代码
<template>
  <h2>我是Home组件的内容</h2>
</template>

<script>
    export default {
        name:'Home'
    }
</script>

src/components/About.vue:

vue 复制代码
<template>
  <h2>我是About组件的内容</h2>
</template>

<script>
    export default {
        name:'About'
    }
</script>
6.3、注意事项

路由组件通常存放在pages文件夹,一般组件通常存放在components文件夹

6.4、多级路由
  • 配置路由规则,使用children配置项:

    js 复制代码
    routes: [
        {
            path: '/about',
            component: About,
        },
        {
            path: '/home'
            component: Home,
            children: [
            {
            	path: 'news',  //注意此处一定不要写 : /news
            	component: News
        	},
        	{
                path: 'message',
                component: Message
            }
            ]
        }
    ]
  • 跳转(要写完整的路径):News

6.5、query()
  1. 传递参数

    vue 复制代码
    <!-- 跳转并携带query参数,to的字符串写法 -->
    <router-link :to="/home/message/detail?id=666&title=你好">跳转</router-link>
    				
    <!-- 跳转并携带query参数,to的对象写法 -->
    <router-link :to="{
    	path:'/home/message/detail',
    	query:{
    		id:666,
            title:'你好'
    	}
    }">跳转</router-link>
  2. 接受参数

vue 复制代码
$route.query.id
$route.query.title

src/router.index.js:

vue 复制代码
//引入路由
import VueRouter from "vue-router"
//引入组件
import Home from '../pages/Home'
import About from '../pages/About'
import News from '../pages/News'
import Message from '../pages/Message'
import Detail from '../pages/Detail'

//创建一个并且暴露一个路由器
export default VueRouter({
	routes: [
	 {
            path:'/about',
            component:About
        },
        {
            path:'/home',
            component:Home,
            children:[
                {
                    path:'news',
                    component:News
                },
                {
                    path:'message',
                    component:Message,
                    children:[
                        {
                            path:'detail',
                            component:Detail
                        }
                    ]
                }
]
})

src/pages/Detail.vue:

vue 复制代码
<template>
    <ul>
        <li>消息编号:{{$route.query.id}}</li>
        <li>消息标题:{{$route.query.title}}</li>
    </ul>
</template>

<script>
    export default {
        name:'Detail'
    }
</script>
6.6、命名路由

作用:简化路由的跳转

使用:

  1. 给路由命名:

    vue 复制代码
    {
    	path: '/demo',
    	component: Test,
    	children: [
    	{
    		path: 'text',
    		component: Text,
    		children: [
    			{
    				name: 'hello'  //命名
    				path: 'welcome',
    				component: Hello
                }
    		]
    	}
    ]
    }
  2. 简化跳转:

vue 复制代码
<!--简化前,需要写完整的路径 -->
<router-link to="/demo/test/welcome">跳转</router-link>

<!--简化后,直接通过名字跳转 -->
<router-link :to="{name:'hello'}">跳转</router-link>

<!--简化写法配合传递参数 -->
<router-link 
	:to="{
		name:'hello',
		query:{
		    id:666,
            title:'你好'
		}
	}"
>跳转</router-link>
6.7、路由的params参数
  1. 配置路由,声明接收params参数

    vue 复制代码
    {
    	path:'/home',
    	component:Home,
    	children:[
    		{
    			path:'news',
    			component:News
    		},
    		{
    			component:Message,
    			children:[
    				{
    					name:'xiangqing',
    					path:'detail/:id/:title', //使用占位符声明接收params参数
    					component:Detail
    				}
    			]
    		}
    	]
    }
  2. 传递参数

    vue 复制代码
    <!-- 跳转并携带params参数,to的字符串写法 -->
    <router-link :to="/home/message/detail/666/你好">跳转</router-link>
    				
    <!-- 跳转并携带params参数,to的对象写法 -->
    <router-link 
    	:to="{
    		name:'xiangqing',
    		params:{
    		   id:666,
                title:'你好'
    		}
    	}"
    >跳转</router-link>
  3. 接收参数

vue 复制代码
$route.params.id
$route.params.title
6.8、props配置
  • 作用:让路由组件方便收到参数

    js 复制代码
    {
    	name:'xiangqing',
    	path:'detail/:id',
    	component:Detail,
    
    	//第一种写法:props值为对象,该对象中所有的key-value的组合最终都会通过props传给Detail组件
    	// props:{a:900}
    
    	//第二种写法:props值为布尔值,布尔值为true,则把路由收到的所有params参数通过props传给Detail组件
    	// props:true
    	
    	//第三种写法:props值为函数,该函数返回的对象中每一组key-value都会通过props传给Detail组件
    	props(route){
    		return {
    			id:$route.query.id,
    			title:$route.query.title
    		}
    	}
    }
    6.9、路由跳转replace()
    1. 作用:控制路由跳转时操作浏览器历史记录的模式
    2. 浏览器的历史记录有两种写入方式:push和replace,其中push是追加历史记录,replace是替换当前记录。路由跳转时候默认为push方式
    3. 开启replace模式:<router-link replace ...>News
相关推荐
Boilermaker19925 分钟前
【Java EE】SpringIoC
前端·数据库·spring
中微子16 分钟前
JavaScript 防抖与节流:从原理到实践的完整指南
前端·javascript
天天向上102431 分钟前
Vue 配置打包后可编辑的变量
前端·javascript·vue.js
芬兰y1 小时前
VUE 带有搜索功能的穿梭框(简单demo)
前端·javascript·vue.js
好果不榨汁1 小时前
qiankun 路由选择不同模式如何书写不同的配置
前端·vue.js
小蜜蜂dry1 小时前
Fetch 笔记
前端·javascript
拾光拾趣录1 小时前
列表分页中的快速翻页竞态问题
前端·javascript
小old弟1 小时前
vue3,你看setup设计详解,也是个人才
前端
Lefan1 小时前
一文了解什么是Dart
前端·flutter·dart
Patrick_Wilson1 小时前
青苔漫染待客迟
前端·设计模式·架构