vue.js 组件的生命周期、组件之间的通讯、处理网络请求及路由模块
1、Vue中组件的生命周期
生命周期:从创建到发展到消亡的过程
分为4个阶段:
create
mount
update
destroy
钩子函数:到指定的时间节点会自动执行的函数
Vue中组件的生命周期的每一个阶段都对应着有一些处理函数
create:做简单的初始化
beforeCreate
created
mount:稍微复杂点的初始化工作。。。
beforeMount
mounted
update:在数据发生变化时,执行一些逻辑处理
beforeUpdate
updated
destroy:在组件销毁时,执行清理工作
beforeDestroy
destroyed
2、Vue中组件之间的通讯
①父与子
props down 借助于属性来完成值的传递
步骤1:父组件调用子组件时,借助自定义属性传值
<son myTitle='张三'></son>
步骤2:子组件借助于props属性来接收数据
Vue.component('son',{
props:['myTitle']
//this.myTitle
})
②子与父
events up 借助于事件完成值的传递
子:发送方负责触发事件(触发事件可以发送数据)
this.$emit('eventName',data)
比如: this.$emit('rcvEvent',this.isLogin)
父:接收方负责绑定事件和事件处理函数(接收数据)
handleEvent(msg){
//msg就是son组件内部,触发myEvent事件时,传递来的数据
}
//方案1
<son @myEvent="handleEvent"></son>
//方案2(更灵活)
<son @myEvent="handleEvent($event)"></son>
③兄弟
借助于一个公共的变量来通过事件的绑定和触发
来实现兄弟组件之间的通信工作
var bus = new Vue();
bus.$on('rcvEvent',(msg)=>{})
bus.$emit('rcvEvent',123)
扩充:
父--》子(子组件主动的到父组件) this.$parent
子--》父(父组件主动的到子组件)
步骤1:给子组件指定ref
<son ref="mySon"></son>
步骤2:通过ref找到子组件的实例
this.$refs.mySon
3、Vue中处理网络请求
axios(推荐https://www.kancloud.cn/yunye/axios/234845)
get:
// 为给定 ID 的 user 创建请求
axios.get('/user?ID=12345')
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// 可选地,上面的请求可以这样做
axios.get('/user', {
params: {
ID: 12345
}
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
post:
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
执行多个并发的请求:
function getUserAccount() {
return axios.get('/user/12345');
}
function getUserPermissions() {
return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()])
.then(axios.spread(function (acct, perms) {
// 两个请求现在都执行完成
}));
4、Vue中处理路由模块
路由模块:建立起组件和url之间的映射关系
4.1 基本用法
①引入vue-router.js
②指定一个容器 用来盛放要动态加载的组件
<router-view></router-view>
③创建页面要用的组件类
var MyLogin = Vue.component....
④配置路由词典
var myRoutes = [
{path:'**',component:***},
{}
]
var myRouter = new VueRouter({
routes:myRoutes
})
⑤测试
在地址栏中修改url,是否能够按照路由词典加载访问的组件
4.2 跳转和传参
跳转:
js:
this.$router.push('目的地的路由地址')
this.$router.go(-1) //向后退一页
this.$router.go(1) //向前进一页
标签:<router-link to='目的地的路由地址'></router-link>
传参:
跳转到某一个页面的时候,有些时候需要传递数据给目的地页面
步骤1:发送方、接收方
步骤2:给接收方配置路由地址,在接收方接收数据
步骤3:发送方负责发送数据
举例:list---index--->detail
步骤1:发送list 接收detail
步骤2:给接收方配置路由地址,
/detail --> /detail/:index
在接收方接收数据
this.$route.params.index
步骤3:发送方负责发送数据
this.$router.push('/detail/'+index)
//如果传递的是变量,借助于属性绑定 v-bind简写为:
<router-link :to="'/detail/'+index">{{tmp}}</router-link>
4.3 路由嵌套
所谓的路由嵌套:在一个路由对象中 可以嵌套其它的路由对象
举例:一个应用程序,当前有两个页面构成,分别是login和mail;
在mail又嵌套了收件箱和发件箱
步骤1:按照路由模块的基本使用,先搞定login和mail
步骤2:在准备嵌套其他组件的mail组件中,指定一个盛放组件的容器
<router-view></router-view>
步骤3:完成收件箱和发件箱组件的创建和路由的配置
{
path:'/mail',
component:MailComponent,
children:[
{path:'',component:MailInbox},
{..}
]
}