一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第3天,点击查看活动详情。
12. 箭头函数
- 基本使用
<script>
//箭头函数:也是一种定义函数的方式
//1.定义函数的方式:function
const a = function () {
}
//2.对象字面量中定义函数
const obj = {
b(){
}
}
//3.ES6中的箭头函数
const c = ()=>{
}
</script>
- 参数和返回值
<script>
//1.参数问题
//1.1两个参数
const sum = (num1,num2) => {
return num1 + num2
}
//1.2一个参数
const power = num => {
return num * num
}
//2.函数中
//2.1有多行代码
const test = ()=> {
console.log('hello werld')
}
//2.2只有一行代码
const mul = (num1,num2) => num1 * num2
console.log(mul(10, 10))
</script>
- 箭头函数中this的使用
<script>
//箭头函数中的this引用的是最近作用域中的this
const obj = {
a(){
setTimeout(function () {
console.log(this)
})
setTimeout(()=>{
console.log(this)
})
}
}
</script>
13. vue-router
- vue-router的使用步骤
- 安装vue-router。npm install vue-router --save
- 在模块化工程中使用它 - 导入路由对象,并且调用Vue.use(VueRouter) - 创建路由实例,并且传入路由映射配置 - 在Vue实例中挂在创建的路由实例
- 使用vue-router的步骤 - 创建路由组件 - 配置路由映射:组件和路径映射关系 - 使用路由:通过<router-link>和<router-view>
- router-link和router-view
- <router-link>:该标签是一个vur-router已经内置的组件,它会被渲染成一个<a>标签。
- <router-view>:该标签会根据当前的路径,动态渲染出不同的组件
- 网页的其他内容,比如顶部的标签/导航或者底部的一些版权信息等会和<router-view>处于同一个等级
- 在路由切换时,切换的是<reouter-view>挂载的组件,其他内容不会发生改变
- 代码
- main.js:总的入口
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
new Vue({
el: '#app',
router, //将路由挂载进来
render: h => h(App)
})
- index.js:路由控制
//配置路由相关信息
import VuerRouter from 'vue-router'
import Vue from 'vue'
//懒加载的方式
const Home = () => import('../components/Home')
const About = () => import('../components/About')
const User = () => import('../components/User')
const HomeNews = () => import('../components/HomeNews')
const HomeMessage = () => import('../components/HomeMessage')
const Profile = () => import('../components/Profile')
//1.通过Vue.use(插件),安装插件
Vue.use(VuerRouter)
//2.创建路由对象
const routes = [
{
path: '',
//redirect重定向
redirect: '/home'
},
{
path: '/home',
component: Home,
meta: {
title: 'Home'
},
//子目录
children: [
{
path: '',
redirect: 'news'
},
{
path: 'news',
component: HomeNews
},
{
path: 'message',
component: HomeMessage
}
]
},
{
path: '/about',
component: About,
meta: {
title: 'About'
}
},
{
path: '/user/:userId',
component: User,
meta: {
title: 'User'
}
},
{
path: '/profile',
component: Profile,
meta: {
title: 'Profile'
}
}
]
const router = new VuerRouter({
//配置路由和组件之间的应用关系
routes,
mode: 'history'//hash模式改为history模式,history模式不会有/#出现在路径当中
})
//前置钩子。实现切换目录时,使得标题也切换
router.beforeEach(function (to,from,next) {
//从from跳转到to
document.title = to.matched[0].meta.title
next()
})
//后置钩子
router.afterEach((to,from) => {
// console.log('后置钩子.............')
})
//3.将router对线传入到vue实例中
export default router
- App.vue
<template>
<div id="app">
<!--replace控制能不能返回-->
<!-- router-link默认被渲染成<a>标签,利用tag可以更改类型 -->
<router-link to="/home" tag="button" replace>首页</router-link>
<router-link to="/about" repalce>关于</router-link>
<router-link :to="'/user/'+userId">用户</router-link>
<!-- <router-link to="/profile">档案</router-link>-->
<router-link :to="{path: '/profile',query: {name: 'why',age: 18,height: 1.88}}">档案</router-link>
<button @click="userClick">用户2</button>
<button @click="profileClick">档案2</button>
<!--显示的位置-->
<!--<button @click="homeClick">首页</button>
<button @click="aboutClick">关于</button>-->
<!-- keep-alive使组件不会频繁创建和销毁 -->
<keep-alive exclude="Profile,User">
<router-view></router-view>
</keep-alive>
</div>
</template>
<script>
export default {
name: 'App',
data(){
return{
userId: 'lisi'
}
},
methods: {
homeClick() {
//通过代码的方式修改路由 vue-router
// this.$router.push('/home')
this.$router.replace('/home')
},
aboutClick() {
// this.$router.push('/about')
this.$router.replace('/about')
},
userClick() {
this.$router.push('/user/'+this.userId)
},
profileClick() {
this.$router.push({
path: '/profile',
query: {
name: 'test',
age: 18,
height: 1.88
}
})
}
}
}
</script>
<style>
.router-link-active {
color: #ff0000;
}
</style>
- Home.vue
<template>
<div>
<h2>HOME..............</h2>
<router-link to="/home/news">新闻</router-link>
<router-link to="/home/message">消息</router-link>
<router-view></router-view>
</div>
</template>
<script>
export default {
name: 'Home',
data() {
return {
path: '/home/news'
}
},
//组件被创建时
created () {
console.log('homeCreated.......')
},
//组件破坏时
destroyed () {
console.log('homeDestroyed....')
},
//组件激活时
activated () {
this.$router.push(this.path)
},
//路径跳转之前
beforeRouteLeave(to,from,next) {
this.path = this.$route.path
next()
}
}
</script>
<style scoped>
</style>
- About.vue
<template>
<div>
<h2>ABOUT............</h2>
</div>
</template>
<script>
export default {
name: 'About'
}
</script>
<style scoped>
</style>
- HomeMessage.Vue
<template>
<div>
<ul>
<li>消息1</li>
<li>消息2</li>
<li>消息3</li>
</ul>
</div>
</template>
<script>
export default {
name: 'HomeMessage'
}
</script>
<style scoped>
</style>
- HomeNews.Vue
<template>
<div>
<ul>
<li>新闻1</li>
<li>新闻2</li>
<li>新闻3</li>
</ul>
</div>
</template>
<script>
export default {
name: 'HomeNews'
}
</script>
<style scoped>
</style>
- User.Vue
<template>
<div>
<h2>User.........</h2>
<h2>{{userId}}</h2>
<h2>{{$route.params.userId}}</h2>
</div>
</template>
<script>
export default {
name: 'User',
computed: {
userId() {
//获取到传送过来的参数
return this.$route.params.userId
}
}
}
</script>
<style scoped>
</style>
- Profile.vue
<template>
<div>
<h2>profile.........</h2>
<h2>{{$route.query.name}}</h2>
<h2>{{$route.query.age}}</h2>
<h2>{{$route.query.height}}</h2>
</div>
</template>
<script>
export default {
name: 'Profile'
}
</script>
<style scoped>
</style>
14. Promise
- Promise的作用
- 回调地狱,代码难以维护, 常常第一个的函数的输出是第二个函数的输入这种现象
- promise可以支持多个并发的请求,获取并发请求中的数据
- 这个promise可以解决异步的问题,本身不能说promise是异步的
- Promise包含两个参数resolve和reject
- resolve :异步操作执行成功后的回调函数
- reject:异步操作执行失败后的回调函数
- Promise的基本使用
<script>
//1.使用setTimeOut
// setTimeout(()=>{
// console.log('hello')
// },1000)
//参数->函数(resolve,reject)
//resolve,reject本身又是函数
new Promise((resolve,reject)=>{
//第一次网络请求
setTimeout(()=>{
resolve()
},1000)
}).then(()=>{
//第一次拿到结果处理的代码
console.log('hello resolve')
return new Promise((resolve,reject)=>{
//第二次网络请求
setTimeout(()=>{
resolve()
},1000)
})
}).then(()=>{
//第二次处理的代码
console.log('hello vue')
return new Promise((resolve,reject)=>{
//第三次网络请求
setTimeout(()=>{
resolve()
},1000)
})
}).then(()=>{
//第三次处理的代码
console.log('hello python')
})
//2.什么情况下会用到promise?一般情况下是有异步操作时,使用promise对这个异步操作进行封装
//new -> 构造函数(1.保存了一些状态信息 2.执行传入的函数)
//在执行传入的回调函数时,会传入两个参数,resolve,reject本身又是函数
new Promise((resolve,reject)=>{
setTimeout(()=>{
//成功的时候调用resolve
resolve('testData')
//失败的时候
reject('error message')
},1000)
}).then((data)=>{
//处理data
console.log(data)
}).catch((data)=>{
console.log(data)
})
</script>
- Promise中的all
<script>
Promise.all([
new Promise((resolve,reject)=>{
$.ajax({
url: '',
success: function (data) {
resolve(data)
}
})
}),
new Promise((resolve,reject)=>{
$.ajax({
url: '',
success: function (data) {
resolve(data)
}
})
})
]).then(res=>{
console.log(res)
})
</script>
15. Vuex
- vuex的简单说明
- 为Vue.js应用程序开发的状态管理模式
- 采用集中式存储管理应用的所有组件的状态
- 状态管理的说明
- 可以简单的将其看成把需要多个组件共享的变量全部存储到一个对象里面。
- 将这个对象放在顶层的Vue实例中,让其他组件可以使用
- 代码介绍
- main.js
import Vue from 'vue'
import App from './App'
import store from './store'
Vue.config.productionTip = false
new Vue({
el: '#app',
store, //来挂载vuex
render: h => h(App)
})
- index.js
import Vue from 'vue'
import Vuex from 'vuex'
import {INCREMENT} from './mutations-types'
//1.安装插件
Vue.use(Vuex)
//2.创建
const moduleA = {
state: {
name: 'zh'
},
mutations: {
updateName(state,payload) {
state.name = payload
}
},
actions: {
aUpdateName(context) {
setTimeout(()=>{
context.commit('updateName','li')
},1000)
}
},
getters: {
fullname(state) {
return state.name + '1111'
},
fullname2(state,getters) {
return getters.fullname + '2222'
},
fullname3(state,getters,rootState) {
return getters.fullname2 + rootState.counter
}
}
}
const store = new Vuex.Store({
//保存状态的
state: {
counter: 10,
students: [
{id:1,name:'w',age:18},
{id:2,name:'h',age:19},
{id:3,name:'y',age:20}
]
},
//定义方法
mutations: {
[INCREMENT](state) {
state.counter++
},
decrement(state) {
state.counter--
},
incrementCount(state,count/*payload*/) {
state.counter += count
//state.counter += payload.count
},
addStudent(state,stu) {
state.students.push(stu)
}
},
actions: {
//类似于mutations,这个是用来进行异步操作的
aUpdateInfo(context,payload) {
return new Promise((resolve, reject) => {
setTimeout(()=>{
context.commit('addStudent')
console.log(payload())
resolve()
},1000)
})
}
},
getters: {
//类似于计算属性
powerCounter(state) {
return state.counter * state.counter
},
more20stu(state) {
return state.students.filter(s => s.age >= 20)
},
more20stuLen(state,getters) {
return getters.more20stu.length
},
moreAgeStu(state) {
return function (age) {
return state.students.filter(s => s.age>age)
}
}
},
//细分模块
modules: {
a: moduleA
}
})
//3.导出
export default store
- App.vue
<template>
<div id="app">
<h2>--------APP内容-----------</h2>
<h2>{{$store.state.counter}}</h2>
<button @click="addition">+</button>
<button @click="subtraction">-</button>
<button @click="addCount(5)">+5</button>
<button @click="addCount(10)">+10</button>
<button @click="addStudent">添加学生</button>
<h2>---------Hello Vuex内容------</h2>
<hello-vuex></hello-vuex>
<h2>App内容:getters相关信息</h2>
<h2>{{$store.getters.powerCounter}}</h2>
<h2>{{$store.getters.more20stu}}</h2>
<h2>{{$store.getters.more20stuLen}}</h2>
<h2>{{$store.getters.moreAgeStu(18)}}</h2>
<h2>App内容:modules中的内容</h2>
<h2>{{$store.state.a.name}}</h2>
<h2>{{$store.getters.fullname}}</h2>
<h2>{{$store.getters.fullname2}}</h2>
<h2>{{$store.getters.fullname3}}</h2>
<button @click="updateName">修改名字</button>
<button @click="asyncUpdateName">异步修改名字</button>
</div>
</template>
<script>
import HelloVuex from './components/HelloVuex'
import {INCREMENT} from './store/mutations-types'
export default {
name: 'App',
data() {
return {
message: 'vuex'
}
},
components: {
HelloVuex
},
methods: {
addition() {
this.$store.commit(INCREMENT)
},
subtraction() {
this.$store.commit('decrement')
},
addCount(count) {
//payload:负载
//1.普通提交风格
this.$store.commit('incrementCount',count)
//2.特殊的提交封装
// this.$store.commit({
// type: 'incrementCount',
// count
// })
},
addStudent() {
const stu = {id:4,name:'why',age:21}
//this.$store.commit('addStudent',stu)
this.$store.dispatch('aUpdateInfo','我是携带的信息')
.then(res => {
console.log("里面提交完成了");
})
},
updateName(){
this.$store.commit('updateName','ang')
},
asyncUpdateName() {
this.$store.dispatch('aUpdateName')
}
}
}
</script>
<style>
</style>
- HelloVuex.vue
<template>
<div>
<h2>{{$store.state.counter}}</h2>
</div>
</template>
<script>
export default {
name: 'HelloVuex'
}
</script>
<style scoped>
</style>
- mutations-types.js
export const INCREMENT = 'increment'
- actions.js和getters.js和mutation.js是将index.js中单独抽离出来,然后用index_copy.js来整合
import Vue from 'vue'
import Vuex from 'vuex'
import mutations from './mutations'
import actions from './actions'
import getters from './getters'
import moduleA from './modules/moduleA'
Vue.use(Vuex)
const state = {
counter: 10,
students: [
{id:1,name:'w',age:18},
{id:2,name:'h',age:19},
{id:3,name:'y',age:20}
]
}
const store = new Vuex.Store({
state,
mutations,
actions,
getters,
modules: {
a: moduleA
}
})
//3.导出
export default store
16. axios
- 简单说明
- axios主要是用于向后台发起请求的,还有在请求中做更多是可控功能。基于Promise语法的。
- 基本使用
- main.js
import Vue from 'vue'
import App from './App'
import axios from 'axios'
Vue.config.productionTip = false
new Vue({
el: '#app',
render: h => h(App)
})
//1.
// axios({
// url: 'http://123.207.32.32:8000/home/multidata',
// //专门针对get请求的参数拼接
// param: {
// type: 'pop',
// page: 1
// }
// }).then( result => {
// console.log(result)
// })
//2.axios发送并发请求
// axios.all([axios({
// url: 'http://123.207.32.32:8000/home/multidata'
// }),axios({
// url: 'http://123.207.32.32:8000/home/data',
// param: {
// type: 'sell',
// page: 2
// }
// })]).then(result => {
// console.log(result)
// })
//3.使用全局配置在进行访问时
// axios.defaults.baseURL = 'http://123.207.32.32:8000'
// axios.defaults.timeout = 5000 //单位是毫秒
//
// axios.all([axios({
// url: '/home/multidata'
// }),axios({
// url: '/home/data',
// param: {
// type: 'sell',
// page: 2
// }
// })]).then(axios.spread(res1,res2 => {
// console.log(res1)
// console.log(res2)
// }))
//4.创建axios的实例
// const instance1 = axios.create({
// baseURL: 'http://123.207.32.32:8000',
// timeout: 5000
// })
//
// instance1({
// url: '/home/multidata'
// }).then(res => {
// console.log(res)
// })
//
// instance1({
// url: '/home/data',
// params: {
// type: 'sell',
// page: 1
// }
// }).then(res => {
// console.log(res)
// })
//
// const instance2 = axios.create({
// baseURL: 'http://111.222.32.32:8000',
// timeout: 4000
// })
//5.封装request模块
import {request} from './network/request'
request({
url: '/home'
}).then(res => {
}).catch(err => {
})
// request({
// url:'/home/multidata'
// },success => {
// console.log(success)
// },failure => {
// console.log(failure)
// })
//
// request({
// baseConfig: {
//
// },
// success: function (result) {
//
// },
// failure: function (error) {
//
// }
// })
- request.js:分离写法
import axios from 'axios'
export function request (config) {
const instance = axios.create({
baseURL: 'http://www.baidu.com',
timeout: 5000
})
//axios的拦截器
instance.interceptors.request.use(config => {
//请求成功
console.log(config)
//1.config中的某些信息不符合要求
//2.每次发送网络请求时,显示一个请求的图标
//3.某些网络请求时必须携带一些特殊的信息
return config
},err => {
//请求失败
console.log(err)
})
instance.interceptors.response.use(res => {
console.log(res)
return res.data
},err => {
console.log(err)
})
return instance(config)
}
// export function request (config) {
// return new Promise((resolve, reject) => {
// const instance = axios.create({
// baseURL: 'http://www.baidu.com',
// timeout: 5000
// })
//
// instance(config)
// .then(res => {
// resolve(res)
// })
// .catch(err => {
// reject(err)
// })
// })
// }
// export function request (config) {
// //1.创建axios实例
// const instance = axios.create({
// baseURL: 'http://123.207.32.32:8000',
// timeout: 5000
// })
//
// instance(config.baseConfig)
// .then(res => {
// config.success(res)
// })
// .catch(err => {
// config.failure(err)
// })
// }
//
// export function request (config,success,failure) {
// //1.创建axios实例
// const instance = axios.create({
// baseURL: 'http://123.207.32.32:8000',
// timeout: 5000
// })
//
// instance(config)
// .then(res => {
// success(res)
// })
// .catch(err => {
// failure(err)
// })
// }
- App.vue
<template>
<div id="app">
</div>
</template>
<script>
export default {
name: 'App',
components: {
}
}
</script>
<style>
</style>