vue2创建项目,路由传参,父子通信,爷孙通信

340 阅读1分钟

1 , 安装更新vue-cli

npm i -g @vue/cli

2 , 创建项目

vue create myproject

3 , 动态组件

<component :is="Title"><component>

Title为变量 Title = 'A' 则显示A组件 , Title='B' 则显示B组件

4 , 缓存组件

<keep-alive><component :is="Title"><component> </keep-alive>

缓存组件多两个生命周期,activated() deactivated() 激活和失活

如果需要重新加载请求就写在activated里

5 , redirect :"/home" 路由重定向

6 , 编程式路由

this.$router.push('/home') 跳转到其他页面

this.$router.go(-1) 跳转到前一页 ,正数前进,负数倒退

this.$router.back() 回到上一页

this.$router.forward() 前进到下一页

this.$router.replace() 跳转到其他页面,覆盖掉前一页的浏览记录

7 , 命名式路由

<router-link :to='{name:"Home"}'></router-link> 匹配路由中的name

8 , 路由元信息

document.title = "首页" 改变当前页的title 需要单独修改,麻烦

meta:{

    title:'首页' 在路由元信息中修改当前页面的title

}

this.$router 是项目的路由实例

this.$route 当前页面的路由对象

linkActiveClass:"active" router-link 标签的路由导航高亮自定义类名

9 , 动态路由

path:"/new/:id"

this.$route.params.id 可以获取当前传参

this.$router.push({ // params 传参

    path:"/home",

    name:"Home", // 必须要,不然接收不到传递的参数

    params:{

        tel:"123"

    }

})

query 传参

this.$router.push({

    path:"/home",

    query:{

        id:"456"
        
        }
    
    })

10,父子传参

父传子
<Child :sendChild="fromFather"/>
子组件中 props:['sendChild']

子传父 
$emit('sendFather','fromChild')
<Child @sendFather="sendFather"/>
父组件中 sendFther(val){
    console.log(val)
}

爷传孙动态响应
provide(){
    return {
        msg:()=>this.msg
    }
}
孙组件中
inject:['msg'],
computed:{
    getmsg(){
        return this.msg()
    }
}