8. view - Router

A, Vue Router uses

JavaScript:
    1.创建组件:创建单页面应用需要渲染的组件
    2.创建路由:创建VueRouter实例
    3.映射路由:调用VueRouter实例的map方法
    4.启动路由:调用VueRouter实例的start方法
 
HTML:
    1.使用v-link指令
    2.使用<router-view>标签

router.redirect:
    1.应用在首次运行时右侧是一片空白,应用通常都会有一个首页,例如:Home页。
    2.使用router.redirect方法将根路径重定向到/home路径:
    router.redirect({'/': '/home'})
    router.redirect 方法用于为路由器定义全局的重定向规则,全局的重定向会
                   在匹配当前路径之前执行。
                   
执行过程:
    当用户点击v-link指令元素时,我们可以大致猜想一下这中间发生了什么事情:
    1.vue-router首先会去查找v-link指令的路由映射
    2.然后根据路由映射找到匹配的组件
    3.最后将组件渲染到<router-view>标签

1. The introduction of plug-Vue and Vue-Router

<script src="vue.js"></script>
<script src="vue-router.js"></script>

2. HTML

<div id="box"> 

</div>
<!--定义模版-->
<template id="a">
    <div>
        第一个router
    </div>
</template>
<template id="b">
    <div>
        第二个router
    </div>
</template>

3. js

let routes = [
    {
        path:'/home',
        component:{template:'#a'},
    },
    {
        path:"/two",
        component:{template:"#b"}
    },
];
// 定义路由组件
let router = new VueRouter({
    routes
});
// 定义路由
new Vue({
    el:"#box",
    router,
})

4. The template adds links

<div id="box"> 
    <router-link to="/one">One</router-link>
    <router-link to="/two">Two</router-link>
    <router-view></router-view>
</div>
< router-link > 默认会被渲染成一个 <a> 标签 >>>to=""为我们定义的路由
< router-view > 路由匹配到的组件将渲染在这里

The simple example

<div id="app">
    <h1>路飞学城</h1>
    <!--<router-link to="/home">首页</router-link>-->
    <!--<router-link to="/course">免费课程</router-link>-->
    <!-- 命名路由,to前要加冒号 -->
    <router-link :to="{name:'home'}">首页</router-link>
    <router-link :to="{name:'course'}">免费课程</router-link>
    <!-- 路由出口 -->
    <router-view></router-view>
</div>

<script>
    let Home = {
        template: `
            <div>
                <h1>首页</h1>
            </div>`,
    };
    let Course = {
        template: `
            <div>
                <h1>免费课程</h1>
            </div>`,
    };
    let router = new VueRouter({
        mode: 'history',
        routes: [
            // 路径重定向
            {path: '', redirect: '/home'},
            // 命名路由
            {path: '/home', name: 'home', component: Home},
            {path: '/course', name: 'course', component: Course},
        ]
    });
    let app = new Vue({
        el: '#app',
        router: router,
    })
</script>

Note: mode: 'history' => default hash, but there will be a problem after writing this url

Second, additional knowledge

1, Vue Router defined

For such progressive distal Vue development framework, in order to construct SPA (single-page applications), the need to introduce the distal end routing system (Vue-Router). Core front-end routing - while not changing the view request to the backend.

2, the browser provides two support (hash / history)

(1) hash - that is, the URL address bar of the # symbol (this is not a cryptographic hash in the hash operation).

Such as the the URL of: http://www.abc.com/#/hello,hash value of # / hello. It is characterized by: hash, although present in the URL, but will not be included in the HTTP request, there is no effect on the back end, thus changing the hash will not reload the page.

(2) history - in the use of new HTML5 History Interface to pushState () and replaceState () method. (Requires a specific browser support)

(3) summary

These two methods used in the browser's history stack, the current existing back, forward, foundation go on top, they provide functionality to modify history. Only when they perform the modification, although the change of the current URL, but not the browser sends a request to the backend immediately. hash history mode and Browser mode belong own characteristics, Vue-Router using only these two properties (by calling the interface provides a browser) to achieve front end routing.

the hash mode, only the hash symbols before content is included in the request, such as http://www.abc.com, so the rear end, even if there is no route to achieve full coverage, does not return 404 error.

the history mode, the front end of the URL and the URL must initiate a request to the rear end of the actual consistency, such as http://www.abc.com/book/id. If the backend lack of / book / id route processing, returns a 404 error. Vue-Router official website in such a description: "However, this mode you want to play well, but also the background configuration support ...... So, you want to add a candidate resources to cover all situations in the service side: if the URL match any static resources, you should return the same index.html page, which is dependent on your app page.

// 字符串
<router-link to="apple"> to apple</router-link>
// 对象
<router-link :to="{path:'apple'}"> to apple</router-link>
// 命名路由
<router-link :to="{name: 'applename'}"> to apple</router-link>
//直接路由带查询参数query,地址栏变成 /apple?color=red
<router-link :to="{path: 'apple', query: {color: 'red' }}"> to apple</router-link>
// 命名路由带查询参数query,地址栏变成/apple?color=red
<router-link :to="{name: 'applename', query: {color: 'red' }}"> to apple</router-link>
//直接路由带路由参数params,params 不生效,如果提供了 path,params 会被忽略
<router-link :to="{path: 'apple', params: { color: 'red' }}"> to apple</router-link>
// 命名路由带路由参数params,地址栏是/apple/red
<router-link :to="{name: 'applename', params: { color: 'red' }}"> to apple</router-link>

4. router.push(...)

// 字符串
router.push('apple')
// 对象
router.push({path:'apple'})
// 命名路由
router.push({name: 'applename'})
//直接路由带查询参数query,地址栏变成 /apple?color=red
router.push({path: 'apple', query: {color: 'red' }})
// 命名路由带查询参数query,地址栏变成/apple?color=red
router.push({name: 'applename', query: {color: 'red' }})
//直接路由带路由参数params,params 不生效,如果提供了 path,params 会被忽略
router.push({path:'applename', params:{ color: 'red' }})
// 命名路由带路由参数params,地址栏是/apple/red
router.push({name:'applename', params:{ color: 'red' }})

5. Remarks

(1) routing summary of the arguments
(1)无论是直接路由“path"还是命名路由“name”,带查询参数query,地址栏会变成“/url?查询
(2)参数名:查询参数值“;
(3)直接路由“path" 带路由参数params params 不生效;
(4)命名路由“name" 带路由参数params 地址栏保持是“/url/路由参数值”;
(2) disposed in the path routing map value
带路由参数params时,路由map里的path应该写成:  path:'/apple/:color' ;
带查询参数query时,路由map里的path应该写成: path:'/apple' ;
(3) The method of acquisition parameters
在组件中:  {{$route.params.color}}
在js里: this.$route.params.color

6. vue parameter passing from one page to another page

(1) First, the definition home.vue
updates(id){
    this.$router.push({
    path:'/world',
    name:'world',
    params:{
        id : id
        }
    })
}
(2) defined in the world.vue
export default {
    name: '',
    data () {
      return {
        id: ''
      }
    },
    created(){
       this.getParams()
    },
    methods: {
      getParams () {
        // 取到路由带过来的参数 
        var routerParams = this.$route.params.id
        // 将数据放在当前组件的数据内
        this.id = routerParams
      }
    },
    watch: {
    // 监测路由变化,只要变化了就调用获取路由参数方法将数据存储本组件即可
      '$route': 'getParams'
    }
  }

Three, Vue nested routing

1. Definitions

Nested routing a demand scenario, assume that the user be able to access content via the path / home / news and / home / mesages, a path mapping a component, the two access paths are also rendering the two components.

2. Example

let UserInfo = {
        template: `
            <div>
                这是用户信息
            </div>`
    };
let UserPost = {
        template: `
            <div>
                这是用户请求
            </div>`
    };

// 2. 定义路由
let router = new VueRouter({
    // mode: 'history',
    routes: [
    {
        path: '/user/:id',
        name: 'user',
        component: User,
        children:[
            {path:'userinfo', component: UserInfo},
            {path:'userpost', component: UserPost},],
            },
        ]
});

Fourth, the route object

https://www.cnblogs.com/avon/p/5943008.html

在使用了 vue-router 的应用中,路由对象会被注入每个组件中,赋值为 this.$route ,
并且当路由切换时,路由对象会被更新。
路由对象暴露了以下属性:
1.$route.path 
  字符串,等于当前路由对象的路径,会被解析为绝对路径,如 "/home/news" 。
2.$route.params 
  对象,包含路由中的动态片段和全匹配片段的键值对
3.$route.query 
  对象,包含路由中查询参数的键值对。例如,对于/home/news/detail/01?favorite=yes
 会得到$route.query.favorite == 'yes' 。
4.$route.router 
  路由规则所属的路由器(以及其所属的组件)。
5.$route.matched 
  数组,包含当前匹配的路径中所包含的所有片段所对应的配置参数对象。
6.$route.name 
  当前路径的名字,如果没有使用具名路径,则名字为空。
  • this. $ router corresponds to the current routing of the object app

  • this. $ route corresponds to the current routing information

  • Route switching required to watch the listener listens

// 怎么查看每一次路由切换之后的当前路由信息呢?
watch: {
    '$route': function (to, from) {
    console.log(to);  // 要切换到的路由信息
    console.log(from);  // 切换前的路由信息
    // ajax 请求数据
    // this.data.courseList
    }
}

Fifth, dynamic routing match

1. HTML

<div id="app">
    <router-link :to="{name:'user', params:{id: 10}}">alex</router-link>
    <router-view></router-view>
</div>

2. js

let User = {
        template: `
            <div>
                <h1>这是{{ this.$route.params.id }}的个人中心页面</h1>
                <p>当前路由的query信息{{ this.$route.query.key }}</p>
            </div>`,
};

let router = new VueRouter({
        // mode: 'history',
        routes: [
            // 添加参数冒号
            // id(id可随便取名,标识),这个属性id可以在$route.params.id中获取
            {path: '/user/:id', name: 'user', component: User},
        ]

});
    
let app = new Vue({
        el: '#app',
        data: {

        },
        router: router,
})

3. Remember two parameters

(1) this. $ Route.params acquisition parameters in the URL

(2) this. $ Route.query get query parameters in the URL

Sixth, programming navigation

// 用代码控制页面跳转;定义课程页组件
    let Course = {
        template: `<div>
            <h1>这是免费课程页面!</h1>
            <button v-on:click="toHome">返回主页</button>
        </div>`,
        methods: {
            toHome(){
                // 编程式导航 (用代码控制页面跳转)
                this.$router.push({name: 'home'})
            }
        }
    };

Guess you like

Origin www.cnblogs.com/hq82/p/11670986.html