Vue routing usage and component extension

1.

  • Accept the value passed by the parent component

Set the props attribute to accept the value passed by the parent component

Parent component passes value to child component

  • Set delivery type

props: {

        // It stipulates that the parent component can only pass object types

        prop1:Object

        // Multiple types can be set, you can pass Number or String

         parentMsg: [Number, String],

        list: {

            // Set type

            type: Array,// [Array,String]

            // Functions must be used when setting default values. The principle is the same as data must use functions.

            default: function () {

                    return [{

                        name: 'This is a default name'

                    }]

            }

        },

}

  • Inheritance and transfer of properties

Characteristics of property inheritance:

The properties of the parent component will override the properties of the child component.

class and style will be merged and will not be overwritten.

Set disable inheritance

Attributes added to child components. Using this attribute will prevent the component from inheriting the attributes of the parent component, except for class and style.

inheritAttrs: false

  • Precautions 

The difference between data and props

Data is private to the component, and props are passed from the parent component.

data can be modified, props are read-only

1.6 Subcomponent passes value to parent component

The child component calls the method of the parent component

  1. Register an event in the parent component for the referenced child component (the name of this event is customized)

  2. Subcomponents can trigger this event $emit('event name')

Child component passes data to parent component

  1. The second parameter of the $emit method can define the content passed by the child component to the parent component.

  2. How to get this content in the parent component

2.1 This method of the parent component does not have custom parameters. You can get it by directly adding this parameter to the method of the parent component.

2.2 The parent component has custom parameters. You can pass in $event and get the data passed by the child component. Only the first parameter can be passed through $event.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>组件自定义事件</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
</head>
<body>
    <!-- 1.给组件添加事件 -->
    <div id="app">
        <son v-on:click-son='clickParent($event,"自定义参数")' v-on:click-son2='clickParent2'></son>
    </div>
    <template id='sonTemp'>
        <div>
            <button @click='clickSon'>点击事件</button>
            <button @click='clickSon2'>点击事件2</button>
            <h3>这是子组件的内容</h3>
        </div>
    </template>
    <script>
        var son = {
            template: '#sonTemp',
            methods: {
                clickSon() {
                    console.log('子组件的方法');
                    // 2. 在子组件中触发这个事件
                    // 发射,触发
                    // 通过这种方式,子组件也可以给父组件传值
                    this.$emit('click-son', {
                        name: '张三'
                    })
                },
                clickSon2(){
                    console.log('子组件的方法2');
                    this.$emit('click-son2', 'nihao')
                }
            },
        }
        var vm = new Vue({
            el: '#app',
            data: {},
            methods: {
                // e是接受子组件传过来的参数,msg是这个方法自己参数
                clickParent(e, msg) {
                    console.log(e);
                    console.log('父组件的方法,数据为:' + msg);
                },
                clickParent2(e) {
                    console.log(e);
                }
            },
            components: {
                son
            }
        })
    </script>
</body>
</html>
  • After the child component is updated, the parent component is updated synchronously

  1. After the child component updates data, notify the parent component

1.1 Register an event when the parent component refers to the child component

1.2 After the child component updates the data, call the $emit method to notify the parent component

1.8 Use of ref

  • Get dom node

  1. Marking the ref attribute for the dom node can be understood as giving the dom node a name.

  2. After adding ref, there is an additional reference to this element in the $refs attribute.

  3. Get this dom element through the $refs attribute of the vue instance.

  • Get component

Example:

<router-link to='/login'>登录</router-link>

<router-link to='/registry'>注册</router-link>

route redirect

redirect can redirect the route

Highlight the selected route

Set router-link-active directly

Configure linkActiveClass:'custom class name'

  1. Marking the ref attribute on a component can be understood as giving the component a name.

  2. After adding ref, there is an additional reference to this component in the $refs attribute.

  3. Get the reference to this component through the $refs attribute of the vue instance, and then you can use this reference to call the method of the subcomponent or get the data of the subcomponent.

  4. 2. Use of routing in Vue

    2.1 What is routing

  5. Back-end routing: For ordinary websites, all hyperlinks are URL addresses, and all URL addresses correspond to the corresponding resources on the server.

  6. Front-end routing: For single-page applications, switching between different pages is mainly achieved through the hash (#) in the URL. At the same time, hash has a characteristic: the HTTP request will not contain hash-related content; therefore, Page jumps in single-page programs are mainly implemented using hash;

  7. In a single-page application, this method of switching pages through hash changes is called front-end routing (different from back-end routing)

  8. 2.2 How to use routing

  9. Router installation

  10. Introduce the js file. This js needs to be placed behind the vue js and automatically installed (a VueRouter construction method is provided)

  11. Create route new VueRouter(), the accepted parameter is an object

  12. Configure the attribute routes:[] in the instantiated object. The object in this array contains the path attribute and the component attribute.

  13. The path attribute is the address of the url, and the component attribute is the displayed component (the object passing the component)

  14. The created route needs to be associated with the vue instance

  15. Directly quote the cdn provided by the official website

    Basic usage of routing

  16. Where the routed component is displayed <router-view></router-view>

  17. <body>
        <div id="app">
            <!-- 通过路由切换的组件会被放在这里 -->
            <router-view></router-view>
        </div>
        <script>
            const login = {
                template: '<h2>登录</h2>'
            }
            // 这里实例化了一个路由
            const router = new VueRouter({
                routes: [{
                    path: '/login',
                    //这里需要注意的是我们直接组件的对象放在这里
                    component: login
                }]
            });
            var vm = new Vue({
                el: '#app',
                // 把路由挂在到实例上
                router: router
            })
        </script>
    </body>

    Route jump

  18. The router-link tag can set the to attribute

  19. The default is a tag, you can set the package tag through tag

  20. Use default style

  21. Custom style

Define parameters

Add ?parameter name=parameter value after the url through query

Get parameters: $route.query.Parameter name

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>路由传递参数</title>
    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <!-- 引入这个路由组件之后提供了一个VueRouter的构造方法 -->
    <script src="https://unpkg.com/vue-router/dist/vue-router.js"></script>
    <style>
        .router-link-active {
            background-color: aquamarine;
            font-size: 20px;
        }
        .my-active {
            background-color: aquamarine;
            font-size: 20px;
        }
    </style>
</head>
<body>
    <div id="app">
        <!-- 通过路由切换的组件会被放在这里 -->
        <!-- <a href="#/login">登录</a> -->
        <!-- <a href="#/registry">注册</a> -->
        <!-- 通过router-link 进行路由的跳转 -->
        <!-- 通过tag可以指定router-link渲染的界面元素 -->
        <!-- <router-link to='/login' tag='div'>登录</router-link> -->
        <router-link to='/login?id=123&name=张三'>登录</router-link>
        <router-link to='/registry'>注册</router-link>
        <router-link to='/detail?id=999'>某一篇新闻</router-link>
        <router-view></router-view>
    </div>
    <script>
        // 实现简单路由功能的步骤
        // 1. 引入js文件,这个js需要放在vue的js后面,自动安装(提供了一个VueRouter的构造方法)
           // 2. 创建路由new VueRouter(),接受的参数是一个对象
           // 3. 在实例化的对象里配置属性 routes :[],这个数组里的对象包含path属性和component属性
           // 4. path属性是url的地址,component属性就是显示的组件(传组件的对象)
           // 5. 创建的路由需要和vue实例关联一下
           // 6. 路由到的组件显示在哪个位置<router-view></router-view>
        const login = {
            template: '<h2>登录,父组件传递过来的id{
   
   {$route.query.id}},name:{
   
   {$route.query.name}}</h2>'
        }
        const registry = {
            template: '<h2>注册</h2>'
        }
        const newsDetail = {
            template: '<h2>文章的详情</h2>',
            created() {
                console.log(this.$route.query.id);
                // 根据这个id去请求后台数据,获取完整的新闻内容,之后进行展示
            },
        }
        // 这里实例化了一个路由
        const router = new VueRouter({
            linkActiveClass: 'my-active',
            routes: [{
                path: '/',
                // 通过这种方式,在访问/路径的时候会重定向到/login路径
                redirect: '/login'
            }, {
                path: '/login',
                //这里需要注意的是我们直接组件的对象放在这里
                component: login
            }, {
                path: '/registry',
                component: registry
            }, {
                path: '/detail',
                component: newsDetail
            }]
        });
        var vm = new Vue({
            el: '#app',
            // 把路由挂在到实例上
            router: router
        })
    </script>
</body>
</html>

Pass parameters using browser parameters

3.1 Method implementation

3.2 Watch usage

  1. When setting up routing/routing address/: parameter name

  2. Get parameters $route.params.Parameter name

  3. <body>
        <div id="app">
            <!-- 通过路由切换的组件会被放在这里 -->
            <!-- <a href="#/login">登录</a> -->
            <!-- <a href="#/registry">注册</a> -->
            <!-- 通过router-link 进行路由的跳转 -->
            <!-- 通过tag可以指定router-link渲染的界面元素 -->
            <!-- <router-link to='/login' tag='div'>登录</router-link> -->
            <router-link to='/login?id=123&name=张三'>登录</router-link>
            <router-link to='/registry'>注册</router-link>
            <router-link to='/detail/1000'>某一篇新闻</router-link>
            <router-view></router-view>
        </div>
        <script>
          // 实现简单路由功能的步骤
            // 1. 引入js文件,这个js需要放在vue的js后面,自动安装(提供了一个VueRouter的构造方法)
            // 2. 创建路由new VueRouter(),接受的参数是一个对象
            // 3. 在实例化的对象里配置属性 routes :[],这个数组里的对象包含path属性和component属性
            // 4. path属性是url的地址,component属性就是显示的组件(传组件的对象)
            // 5. 创建的路由需要和vue实例关联一下
            // 6. 路由到的组件显示在哪个位置<router-view></router-view>
            const login = {
                template: '<h2>登录,父组件传递过来的id{
         
         {$route.query.id}},name:{
         
         {$route.query.name}}</h2>'
            }
            const registry = {
                template: '<h2>注册</h2>'
            }
            const newsDetail = {
                template: '<h2>文章的详情</h2>',
                created() {
                    console.log(this.$route.params.id);
                    // 根据这个id去请求后台数据,获取完整的新闻内容,之后进行展示
                },
            }
            // 这里实例化了一个路由
            const router = new VueRouter({
                linkActiveClass: 'my-active',
                routes: [{
                    path: '/',
                    // 通过这种方式,在访问/路径的时候会重定向到/login路径
                    redirect: '/login'
                }, {
                    path: '/login',
                    //这里需要注意的是我们直接组件的对象放在这里
                    component: login
                }, {
                    path: '/registry',
                    component: registry
                }, {
                    path: '/detail/:id/:name',
                    component: newsDetail
                }]
            });
            var vm = new Vue({
                el: '#app',
                // 把路由挂在到实例上
                router: router
            })
        </script>
    </body>

    Nesting of components

  4. Set children when declaring the route. Children is an array, and the array is the routing object.

  5. The children component will be rendered in the <router-view> of its parent component.

  6. <body>
        <!-- 通过这个路由的嵌套,我们可以实现一些布局 -->
        <div id="app">
            <router-view></router-view>
        </div>
        <template id="parentCompTemp">
            <div>
                <h1>登录注册页面</h1>
                <router-link to='/parent/login'>登录</router-link>
                <router-link to='/parent/registry'>注册</router-link>
                <router-view></router-view>
            </div>
        </template>
        <script>
            const parentComp = {
                template: '#parentCompTemp'
            }
            const login = {
                template: '<h2>登录</h2>'
            }
            const registry = {
                template: '<h2>注册</h2>'
            }
            const newsDetail = {
                template: '<h2>文章的详情</h2>',
                created() {
                    console.log(this.$route.query.id);
                    // 根据这个id去请求后台数据,获取完整的新闻内容,之后进行展示
                },
            }
            // 这里实例化了一个路由
            const router = new VueRouter({
                linkActiveClass: 'my-active',
                routes: [{
                    path: '/',
                    // 通过这种方式,在访问/路径的时候会重定向到/login路径
                    redirect: '/parent'
                }, {
                    path: '/parent',
                    component: parentComp,
                    // 涉及到了子路由的内容
                    children: [{
                            // 这就是用相对路径,相对于父组件的,这个实际路径就是/parent/login
                            path: 'login',
                            component: login
                        }, {
                            // 这就是用相对路径,相对于父组件的,这个实际路径就是/parent/login
                            path: 'registry',
                            component: registry
                        },
                    ]
                }]
            });
            var vm = new Vue({
                el: '#app',
                // 把路由挂在到实例上
                router: router
            })
        </script>
    </body>

    named view

  7. We used to be able to only have one address correspond to one component, but now we can have one address correspond to multiple components.

  8. components attribute set

  9. Set a name for router-view. This name corresponds to the names of components.

  10. Set the default value. The corresponding component of default can be named and accessed.

  11. 3. Computed properties and listeners

    name case

  12. To get the complete name, you need to splice the last name and first name together.

  13. When to splice them together (when the input value changes)

  14. Monitor keyup to know when the input changes, and you can get the complete name here

3.4 The difference between method, computed and watch

  1. The results of computed properties are cached and will not be recalculated unless the dependent responsive properties change. Mainly used as attributes, do not add () when using;

  2. The methods method represents a specific operation and mainly writes business logic;

  3. Watch is an object, the key is the expression to be observed, and the value is the corresponding callback function. It is mainly used to monitor changes in certain specific data to perform certain specific business logic operations; it can be regarded as a combination of computed and methods.

Guess you like

Origin blog.csdn.net/m0_65849649/article/details/123748189