cnode社区

面试要点:(单页应用重点在vue-router)

  1. 单页应用,页面只有一个 APP组件;
  2. vue-router实现页面内视图跳转,多个router-view可以显示多个组件,router-view根据路由的定位显示组件;
    APP.vue项目结构:
<div id="app">
    <Header></Header>
    <div class="main">
        <router-view name="slidebar"></router-view>
        <router-view name="main"></router-view>
    </div>
</div>
  1. 路由的配置结构
export default new Router({
  routes: [
    {
      name: 'root',
      path: '/',
      components:{
        main: PostList
      }
    },
    {
      name: 'post_content',
      path:'/topic/:id&author=:name',
      components:{
        main:Article,
        slidebar: SlideBar,
      }
    },
    {
      name:'user_info',
      path: '/userinfo/:name',
      components:{
        main: UserInfo,
      }
    }
  ]
})
  • 路由的跳转路径path可以设置参数(前面加:),参数由router-link提供,
<router-link :to="{name:'post_content',params:{id:post.id,name:post.author.loginname}}">
  • 路由跳转后,个人详情页(userInfo)和文章详情页(Article)发送请求获得数据时需要拿到此时路由的上的参数;this.$route.params.XXX
getArticleData(){
  this.$http.get(`https://cnodejs.org/api/v1/topic/${this.$route.params.id}`)
    .then(res=>{
      if(res.data.success == true){
        this.isLoading = false
        this.post = res.data.data
       }
     })
    .catch(err=>{console.log(err)})
}

总结:

router-link 动态绑定 to 属性指定跳转的路由name并提供路由需要的参数
router配置里path需要的参数和vue组件获取路由上的参数都来自router-link。

  1. watch 监听路由的变化
    当路由变化时,需要重新请求数据更新页面,例如在文章详情页点开了另一篇文章的链接,根据路由的变化,重新发送请求拿到数据,所以要使用watch属性监听$route
watch:{
  $route: function(to,from){
    this.getArticleData()
  }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。