Vue Day 4 (communication ref between parent and child components to obtain DOM elements and component routing)

Keywords: Vue Attribute JSON

Vue fourth days

Communication between parent and child components

ref Gets DOM Elements and Components

Route

Parent components pass values to child components

1. Subcomponents use data from parent components
  • Preliminary Attempt (Error Analysis)

  • Correct use method
<div id="app">
    <!--Parent component,You can use attribute binding when referring to subcomponents( v-bind: ) In the form of attribute binding, the data that needs to be passed to the subcomponent is passed to the internal of the subcomponent for use by the subcomponent.-->
    <com1 v-bind:parentmsg="msg"></com1>
</div>
<script>
    let vm = new Vue({
        el: '#app',
        data: {
            msg: '123 Data in parent components'
        },
        methods: {},
        components: {
            com1: {
                //Data in props are read-only and cannot be reassigned.
                props: ['parentmsg'],//The parentmsg attribute passed by the parent component is defined first in the props array so that the data can be used
                template: '<h1>This is a subcomponent---{{parentmsg}}</h1>'
            }
        }
    })
</script>

2. Subcomponents use methods in parent components
<div id="app">
    <com1 @func="show"></com1>
</div>

<template id="tmp1">
    <div>
        <h1>This is a subcomponent</h1>
        <button @click="myclick">This is the button in the subcomponent</button>
    </div>
</template>
<script>
    let com2 = {
        template: '#tmp1',
        methods: {
            myclick() {
                //  emit means trigger, call, launch.
                this.$emit('func')
            }
        }
    }

    let vm = new Vue({
        el: '#app',
        data: {},
        methods: {
            show() {
                console.log('Calling the parent component show Method')
            }
        },
        components: {
            com1: com2
        }
    })
</script>

Subcomponents pass values to parent components

  • Setting parameters (for subcomponents to pass parameters)

  • list data object description
<div id="app">
    <com1 @func="show"></com1>
</div>

<template id="tmp1">
    <div>
        <h1>This is a subcomponent</h1>
        <button @click="myclick">This is the button in the subcomponent.</button>
    </div>
</template>

<script>
    let com2 = {
        template: '#tmp1',
        data () {
            return {
                list: [{'id': '1', 'age': '18'}]
            }
        },
        methods: {
            myclick() {
                // emit means trigger, call, launch.
                this.$emit('func', this.list)
            }
        }
    }

    let vm = new Vue({
        el: '#app',
        data: {},
        methods: {
            show(data) {
                console.log(data)
            }
        },
        components: {
            com1: com2
        }
    })
</script>

Component Case - Comment

Comment case

Knowledge Points Required: Father and Son Components Pass Values, Local Storage Local Storage Storage

Code:

<div id="app">
    <comment-box @func="loadlocalStorage"></comment-box> <!--Comment Component Call-->
    <ul class="list-group">
        <li class="list-group-item" v-for="item in list" :key="item.id">
            <span class="badge">{{item.user}}</span>
            {{item.content}}
        </li>
    </ul>
</div>

<!--Comment Component Template-->
<template id="tmp1">
    <div>
        <div class="form-group">
            <label for="exampleInputEmail1">user: </label>
            <input type="search" class="form-control" 	             		                        id="exampleInputEmail1" placeholder="user" v-model="user">
        </div>
        <div class="form-group">
            <label for="exampleInputEmail2">content: </label>
            <textarea class="form-control" id="exampleInputEmail2" v-model="content"                placeholder="Post a message"></textarea>
        </div>
        <button type="button" class="btn btn-primary" style="margin-bottom: 15px"                       @click="Postcomment">Publish
   </div>
</template>

    <script>
        let commentBox = {
            template: '#tmp1',
            data() {
                return {
                    user: '',
                    content: ''
                }
            },
            methods: {
                Postcomment() {
                    //Analysis: Business logic for commenting
                    //1. Where does the comment data go? Store it in the local Storage.setItem ('cmts',')
                    //2. Organize an up-to-date review data object first
                    //3. Find a way to put the second step, get the comment object. Save to local Storage
                    //   3.1 Local Storage only supports storing string data, first call JSON.stringify
                    //   3.2 Before saving the latest comment data, you first retrieve the previous comment data (string) from the local Storage, convert it into an array object, and then push the latest comment to the array.               
                    //   3.3 If the comment string in the local Storage is empty and does not exist, then a'[]'can be returned and JSON.parse can be converted.
                    //   3.4 Convert the latest comment list array, call JSON.stringify again to the array string, and then call localStorage.setItem()

                    let comment = {id: Date.now(), user: this.user, content: this.content}

                    //Get all the comments from the local Storage
                    let list = JSON.parse(localStorage.getItem('cmts') || '[]')

                    list.unshift(comment)
                    //Re-save the latest comment data
                    localStorage.setItem('cmts', JSON.stringify(list))
                    this.user = this.content = ''
                    this.$emit('func')
                }
            }
        }

        let vm = new Vue({
            el: '#app',
            data: {
                list: [{id: Date.now(), user: 'Li Bai', content: 'Natural talent is useful.'},
                       {id: Date.now(), user: 'Zhang San', content: 'Hoe standing grain gradually pawning a midday'},
                       {id: Date.now(), user: 'Li Si', content: 'By the end of the day'}]
            },
            created() {
                //Load the comment list from the local Storage
                this.list = JSON.parse(localStorage.getItem('cmts') || '[]')
            },
            methods: {
                loadlocalStorage() {
                    this.list = JSON.parse(localStorage.getItem('cmts') || '[]')
                }
            },
            components: {
                commentBox: commentBox
            }
    </script>

ref Gets DOM Elements and Components

ref Gets DOM Elements

  • Basic use
<div id="app">
    <button @click="getElement">Get elements</button>
    <h3 id="myh3" ref="myh3">It's sunny today.</h3>
</div>
<script>
    let vm = new Vue({
        el: '#app',
        data: {},
        methods: {
            getElement() {
                // console.log(document.getElementById('myh3').innerText)
                console.log(this.$refs.myh3.innerText)
            }
        }
    })
</script>

ref acquisition component

<div id="app">
    <button @click="getElement">Get elements</button>
    <h3 id="myh3" ref="myh3">It's sunny today.</h3>
    <hr>
    <login ref="mylogin"></login>
</div>
<script>
    let login = {
        template: '<h1>This is a component.</h1>',
        data() {
            return {
                msg: 'This is the data of the subcomponent.'
            }
        },
        methods: {
            show() {
                console.log('This is a subcomponent show Method')
            }
        }
    }

    let vm = new Vue({
        el: '#app',
        data: {},
        methods: {
            getElement() {
                // console.log(document.getElementById('myh3').innerText)
                // console.log(this.$refs.myh3.innerText)
                console.log(this.$refs.mylogin.msg)
            }
        },
        components: {
            login
        }
    })
</script>

Route

What is routing?

Can refer to

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

Front-end routing: For single-page applications, the handover between different pages is mainly achieved by hash(#) in the URL. At the same time, hash has one feature: HTTP requests do not contain hash-related content; therefore, page Jump in single-page applications is mainly realized by hash;

In single-page applications, this way of switching pages through hash changes is called front-end routing (different from back-end routing); hash in the URL (well number)

Vue Router

Practical small document

  • Basic use of routing
  • Small cases of login and registered routing handover:
<script src="../../vue.min.js"></script>
<!--1.install vue-router Routing module-->
<script src="../vue-router.js"></script>
<div id="app">
    <!--Rearwards a The label will be router-link Replace-->
    <a href="#/login">Land</a>
    <a href="#/register">register</a>
    <!--This is vue-router Provided elements, specifically used as placeholders, will be shown in the future, routing rules, matching components router-view Go in-->
    <!--So: we can put router-view Think of it as a placeholder-->
    <router-view></router-view>
</div>
<script>
    //Component Template Object
    let login = {
        template: '<h1>Landing module</h1>'
    }

    let register = {
        template: '<h1>Registration component</h1>'
    }
    
    //2. Create a routing object. After importing the vue-router package, there is a routing constructor called VueRouter in the window s global object.
    // When new routing objects are used, a configuration object can be passed to the constructor.
    let routerobj = new VueRouter({
        // routes: route in this configuration object denotes the meaning of route Matching Rules
        routes: [//Route Matching Rules
                //Every routing rule is an object. There are two necessary attributes on this rule object.
                //Attribute 1 is path, indicating which route link address;
                //Attribute 2 is a component, indicating that if the route is the path matched earlier, the component corresponding to the component attribute is displayed.
            {path: '/login', component: login},
            {path: '/register', component: register}
        ]
    })

    let vm = new Vue({
        el: '#app',
        data: {
            msg: 'sadsad'
        },
        router: routerobj //Register routing rule objects on vm instances to monitor changes in URL addresses, and then show the corresponding components
    })

</script>

  • The use of router-link (instead of a tag):

  • Home page redirection (root path redirection)

  • Routing highlighting effect

  • Using animation in routing

Defining parameters in routing rules

  • Mode 1:
<div id="app">
    <router-link to="/login?id=10">Land</router-link>
    <router-link to="/register">register</router-link>
    <router-view></router-view>
</div>
<script>
    //Component Template Object
    let login = {
        template: '<h1>Landing module</h1>',
        created() {
            console.log(this.$route)
        }
    }

    let register = {
        template: '<h1>Registration component</h1>'
    }

    let routerobj = new VueRouter({
        routes: [                           //Route Matching Rules
            {path: '/', redirect: '/login'},//Here redirect and redirect in Node are completely different things.
            {path: '/login', component: login},
            {path: '/register', component: register}
        ]
    })

    let vm = new Vue({
        el: '#app',
        data: {
            msg: 'sadsad'
        },
        router: routerobj //Register routing rule objects on vm instances to monitor changes in URL addresses, and then show the corresponding components
    })
</script>

  • Get the parameters and render them on the component

Or: ==> more concise and intuitive!

  • Value transfer mode 2:

Nested routing

  • The Use of children
<div id="app">
    <router-link to="/account">account</router-link>
    <router-view></router-view>
</div>

<template id="tmp1">
    <div>
        <h1>This is account assembly</h1>
        <router-link to="/account/login">Sign in</router-link>
        <router-link to="/account/register">register</router-link>
        <router-view></router-view>
    </div>
</template>
<script>
    let account = {
        template: '#tmp1'
    }

    let login = {
        template: '<h3>login</h3>'
    }

    let register = {
        template: '<h3>register</h3>'
    }

    let router = new VueRouter({
        routes: [{
            path: '/account',
            component: account,
            /*The child attribute is used to implement sub-routing. At the same time, before the path of sub-routing, do not take /.
Otherwise, the request always starts with the root path, which is not convenient for our users to understand the URL address.*/
            children: [
                {path: 'login', component: login},
                {path: 'register', component: register}
            ]
        }]
    })

    let vm = new Vue({
        el: '#app',
        data: {
            msg: 'Ha-ha'
        },
        router
    })
</script>

Routing-Naming View for Classical Layout

  • Named View Implements Classical Layout
<style>
    *{
        margin: 0;
        padding: 0;
    }
    .header{
        height: 80px;
        background: orange;
    }
    .container{
        display: flex;
        height: 400px;
    }
    .left{
        background: #2b542c;
        flex: 2;
    }
    .main{
        background: red;
        flex: 8;

    }
</style>

<div id="app">
    <router-view></router-view>
    <div class="container">
        <router-view name="left"></router-view>
        <router-view name="main"></router-view>
    </div>
</div>

<script>
    let header = {
        template: '<h1 class="header">Header Head region</h1>'
    }
    let leftBox = {
        template: '<h1 class="left">leftBox region</h1>'
    }
    let mainBox = {
        template: '<h1 class="main">mainBox region</h1>'
    }

    let router = new VueRouter({
        routes: [
            // {path:'/',component:header},
            // {path:'/left',component:leftBox},
            // {path:'/main',component:mainBox}
            {
                path: '/', components: {
                    default: header,
                    left: leftBox,
                    main: mainBox
                }
            }
        ]
    })

    let vm = new Vue({
        el: '#app',
        data: {
            msg: 'Ha ha ha'
        },
        router
    })
</script>

Posted by RossC0 on Sat, 18 May 2019 13:55:06 -0700