• Welcome to follow my public number

  • The content of the study is as follows

  • start

  • Parent components pass values to child components

  • The child component can’t access the data in the parent component data, that is, MSG, but there are methods that can access it

  • Data in the child component is not passed by the parent component, but is its own private data,

  • Data that the child component requests back through Ajax

  • The data in data is readable and writable

  • Parentmsg, the property passed from the parent, is defined so that data from the parent can be used

   template:"< h@click ='change'> subcomponent --{{parentmsg}}--".Copy the code
  • Parentmsg, the property passed from the parent, is defined so that data from the parent can be used
  • The data in props was read-only and could not be changed, but it seems that it is now. , and the program does not report errors ????
                props:["parentmsg"].Copy the code
  • [fixed] The props data was read-only and could not be changed, but it seems that it can now be changed.
  • The Demo parent component passes values to its children
<! 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>Document</title>
    <script src="./lib/vue.min.js"></script>
</head>
<body>

    <div id="app"> <! <com1 v-bind:parentmsg= com1 v-bind:parentmsg= com1 v-bind:parentmsg="msg"></com1> </div> <script>"#app".data() {
            return {
                 msg:"Parent component -- I am vUE data"} }, methods: {}, components: {/ / child components can not access to the parent component of data in the data, but cannot access the MSG, but there are ways you can access to the com1: {/ / child component data in the data, and is not passed on the parent component, is a private, // The data in the data is readable and writabledata() {
                   return {
                       title:"dd"
                   }
               },

                template:"< h@click ='change'> subcomponent --{{parentmsg}}--"// The parentmsg property passed by the parent component is read-only and cannot be changed, but it seems that it can now be used. props:["parentmsg"],
                methods: {
                    change(){
                        this.parentmsg=[fixed] The props data was read-only and could not be changed, but it looks like it can now.
                    }
                },
            }
        }
    })
    </script>
</body>
</html>
Copy the code
  • Child components pass values to parent components

  • The child passes a value to the parent, which means that the parent passes a method, the child calls the method, and passes the value to the parent

  • Event binding mechanism, V-on passes the parent component’s show method to the child component’s event

  • V-on can be shortened to the @ sign

        <com2 v-on:event="show"></com2>
Copy the code
  • By specifying an ID, load the contents of the ID’s template element as the HTML structure of the component
template: "#tmpl".Copy the code
  • How to get the parent component method
// How to get the parent component method //emit is willing to trigger, call this.$emit("event", this.ddddd)
                    this.$emit("event"."I am the value passed by the child component.")
                    this.$emit("event", 123456).Copy the code
  • Methods that trigger the parent component

  • Why can’t you print this object ????? I’ve been delayed for 3s. Ahhhhh, I want to print out the value passed by the child component to the parent component, but the code execution gives an error ???? I initially thought the assignment was delayed, and delayed the execution of 3s, but there is still a problem?
 setTimeout(function () {
                        console.log('Executed');
                        console.log(shimingForSon)
                    }, 3000);
Copy the code
  • The Demo child component passes values to its parent
<! 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>Document</title>
    <script src="./lib/vue.min.js"></script> </head> <! -- -- -- > <! The parent passes a method, the child calls the method, and passes the value to the parent --> <body> <div id="app"> <! -- Event binding mechanism, v-on passes the parent component's show method to the child component's event--> <! -- V-ON can be shortened to @ symbol --> <com2 V-on :event="show"></com2>
    </div>

    <template id="tmpl"> <div> <h2> I am a TMPL component </h2> <inputtype="button" value="Click on me to trigger the parent component's method." @click="myDemo"> </div> </template> <script> // define a component template object of literal type var com2 = {// specify an ID to load the contents of the template element of ID, as the HTML structure of the component template:"#tmpl".data() {
                return{// object DDDDD: {name:"Mr. Shiming", age: "18" }
                }
            },
            methods: {
                myDemo() {
                    console.log("I am a child component"// How to get the method from the parent component //emit is willing to trigger, call this.$emit("event", this.ddddd)
                    this.$emit("event"."I am the value passed by the child component.")
                    this.$emit("event"Var vm = new Vue({el:"#app".data() {
                console.log("Data, I'm going to execute.")
                return {
                    msg: "Parent component -- I am vUE data", shimingForSon: null}}, methods: {// Show (data) {console.log("I am the parent component's method show"+ data) console.log(data) this.shimingForSon = data ????? I'm already three seconds latesetTimeout(function () {
                        console.log('Executed');
                        console.log(shimingForSon)
                    }, 3000);
                    // console.log(shimingForSon)


                }
            },
            components: {
                com2
            }

        })
    </script>
</body>

</html>
Copy the code
  • List of Demo reviews
<! 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>Document</title>
    <script src="./lib/vue.min.js"></script> <! --> <link rel="stylesheet" href="./lib/bootstrap.min.css">
</head>

<body>
    <div id="app"> <! The loadData method is passed from parent to child --> < box-@func ="loadData"></box>
        <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>

    <template id="tmpl">

        <div>
            <div class="form-group"> <label> person: </label> <textarea class="form-control" v-model="user"></textarea>
            </div>

            <div class="form-group"</label> <textarea class="form-control" v-model="content"></textarea>
            </div>
            <div class="form-group">
                <input type="button" value="Published" @click="add" class="btn btn-primary">
            </div>
        </div>
    </template>
    <script>
        var commentBox = {
            template: "#tmpl".data() {
                return {
                    user: "",
                    content: "",

                }
            },
            methods: {
                add() {
                    console.log("Click on component") // The data is storedlocal// Organize a new comment data pair to select which // store the object tolocalStorage // attentionlocalStorage supports string data, first call json. stringify // to ensure data integrity, new data should be stored with the old data // note that if the data does not exist, Var commentqq = {id: date.now (), user: this.user, content: This.content} // Get the data locally var strdata =localStorage.getItem("cmts") | |"[]"Parse (strdata) var list = json.parse (strdata) // notice the order // list.push(commentqq) // Is to add data to the header list.unshift(commentqq) // Save data locallylocalStorage.setItem("cmts", json.stringify (list)) // Empty data this.user = this.content =""
                    console.log("Click on the end of the component"+ list + this.user) // func is the method passed by the parent to trigger this method.$emit("func")
                }
            },
        }

        var vm = new Vue({
            el: "#app",
            data: {
                list: [
                    { id: Date.now(), user: "shiming", content: "text" },
                    { id: Date.now(), user: "shiming1", content: "text1" },
                    { id: Date.now(), user: "shiming2", content: "text2" }
                ]
            },
            methods: {
                loadData() {
                    var strdata = localStorage.getItem("cmts") | |"[]"Var list = JSON. Parse (strdata) this.list = list}}, // Initialization is donecreated() {
                this.loadData()
            },
            components: {
                "box": commentBox
            }
        })
    </script>

</body>

</html>
Copy the code
  • refGets references to DOM elements and components
  • To put it more simply, you can use the methods and data of child components
  • console.log(this.$refs.id_h3.innerText)
    <div  id="app">
         <input type="button" value="Get elements" @click="getElement" ref="btn"> <! -- ref can specify the native DOM object --> <h3 id="id_h3"  ref="id_h3"</h3> </div>Copy the code

  • Demo
<! 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>Document</title>

    <script src="./lib/vue.min.js"></script>
</head>

<body>

    <div id="app">
        <input type="button" value="Get elements" @click="getElement" ref="btn"> <! -- ref can specify the native DOM object --> <h3 id="id_h3" ref="id_h3"> Hello </h3> <hr> <! -- The component can also use --> <login ref="myLogin"></login>
        
    </div>
 

    <template id="login"</h1> </template> <script> var login = {template:"#login".data() {
                return {
                    msg:"I am a component."
                }
            },    
            methods: {
                show(){
                    console.log("Method of child component called")
                }
            },
        }
        var vm = new Vue({
            el: "#app",

            data: {

            },

            methods: {
                getElement() {// Get the DOM element by id, but Vue does not recommend // <h3 id="id_h3"> </h3> console.log(document.getelementbyId ("id_h3"))


                    console.log("I'm the method that gets the object of the DOM element in Vue."// ref is reference console.log(this).$refs.id_h3.innerText) // Get the data console.log(this) from the child component.$refs.mylogin. MSG) // calls the child component's method this.$refs.myLogin.show()

                }
            },

            components:{
               "login":login
              
            }
        })
    </script>
</body>

</html>
Copy the code

routing

  • Back-end routing: All urls correspond to resources on the server
  • Front-end routing: For single-page applications, mainly throughURLtheHash (#)Number to achieve switching between different pages, at the same timehashThere is one characteristic,httpThe request will not containashRelated content, so the single page program is mainly throughhashimplementation
  • Use the routing method
  • 1. Import the package
<! -- vue --> <script src="https://unpkg.com/vue/dist/vue.js"></script> <! -- vue routing --> <script SRC ="https://unpkg.com/vue-router/dist/vue-router.js"></script>

Copy the code
  • 2. Define components
  var login = {
            template: "

I am login component

"
} var register = { template: "< H1 > I am a registered component " } Copy the code
  • Note the spelling of routes. There is no r
Const router = new VueRouter({// // Component must be a component template object, not the name of the component application. // Specify that the default is login, // {path:"/",component:login},
                // redirect进入页面的时候,直接就去login组件的页面
                { path: "/", redirect: "/login" },
                { path: "/login", component: login },

                { path: "/register", Component: register}], // Default:"router-link-active"// Set the name of the CSS class to use when the link is activated. The default value can be configured globally with the route construction option linkActiveClass. // Change your style to the desired linkActiveClass:"myStyle"

        })
Copy the code
  • 4. Register with vm
// Register the routing rule object with the VM instance to listen for URL object address changes. Then show the corresponding component router: RouterCopy the code
  • Matters needing attention

  • {path: “/”, redirect: “/login”}

  • Router-link-active Sets the CSS class name to be used when the link is activated. The default value can be configured globally with the route construction option linkActiveClass. LinkActiveClass :”myStyle”

  • Path indicates the address to listen for that routed connection

  • Component must be a template object for a component, not the name of the component application

  • Route parameter transfer mode 1

  • To use k = “/ login? Id =10&name=shiming”

<! -- Router-link defaults rendering to a tag that specifies what tag to render --> <! -- If the query string is used to pass parameters to the route, there is no need to modify the path attribute of the routing rule --> <router-link to="/login? id=10&name=shiming" tag="span"> log in < / router - the link >Copy the code
  • In the componentcreatedMethod to get parameters
// The lifecycle of the componentcreated() {
                console.log("I'm logging in to the component.")
                console.log(this.$route)
                console.log(this.$route.query.id)
            },
Copy the code
  • Get the value for
  • It is then displayed on the control
Var login = {template:"<h1> I am login component {{$route.query.id }}----{{$route.query.name}}</h1>", // The component lifecyclecreated() {
                console.log("I'm logging in to the component.")
                console.log(this.$route)
                console.log(this.$route.query.id)
            },
        }
Copy the code
  • router-link-activeThe meaning of the value:
Router-link-active {color: red; font-weight: 800; Font-size: 16px; /* size */ font-size: 100px; /* underline */ text-indent: underline; /* Background-color: goldenrod}Copy the code
  • Complete the Demo
<! 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>Document</title> <! -- vue --> <script src="https://unpkg.com/vue/dist/vue.js"></script> <! -- vue routing --> <script SRC ="https://unpkg.com/vue-router/dist/vue-router.js"Word-wrap: break-word! Important; "></script> <style> font-weight: 800; Font-size: 16px; /* size */ font-size: 100px; /* underline */ text-indent: underline; /* background-color: goldenrod}. MyStyle {color: hotpink; } .v-enter, .v-leaver-to { opacity: 0; transform: translateX(100px); }. V-enter-active,. V-leaver -active {transition: all 0.5s ease; } </style> </head> <body> <div id="app"> <! -- Not recommended --> <! -- <a href="#/login"</a> <a href="#/register"> Register </a> --> <! -- Router-link defaults rendering to a tag that specifies what tag to render --> <! -- If the query string is used to pass parameters to the route, there is no need to modify the path attribute of the routing rule --> <router-link to="/login? id=10&name=shiming" tag="span"</router-link> <router-link to="/register"> Register </router-link> <! This is an element provided in vue-router for station use --> <! -- Wrap animation mode="out-in"<transition mode="out-in">< router-view></router-view> </transition> </div> <script>"<h1> I am login component {{$route.query.id }}----{{$route.query.name}}</h1>", // The component lifecyclecreated() {
                console.log("I'm logging in to the component.")
                console.log(this.$route)
                console.log(this.$route.query.id)
            },
        }
        var register = {
            template: "< H1 > I am a registered component "} const router = new VueRouter({// // Component must be a component template object, not the name of the component application. // Specify that the default is login, // {path:"/",component:login},
                // redirect进入页面的时候,直接就去login组件的页面
                { path: "/", redirect: "/login" },
                { path: "/login", component: login },

                { path: "/register", Component: register}], // Default:"router-link-active"// Set the name of the CSS class to use when the link is activated. The default value can be configured globally with the route construction option linkActiveClass. // Change your style to the desired linkActiveClass:"myStyle"

        })


        var vm = new Vue({
            el: "#app", data: {}, methods: {}, // Register the routing rule object on the VM instance, which is used to listen for the URL object address change. Router: router Router}) </script> </body> </ HTML >Copy the code
  • Route parameter transfer mode 2
  • 1. Pass in parameters
<! <router-link to=? <router-link to="/login/10/lishiming" tag="span"> log in < / router - the link >Copy the code
  • 2. Router definition{ path: "/login/:id/:name", component: login },
Const router = new VueRouter({// // Component must be a component template object, not the name of the component application. // Specify that the default is login, // {path:"/",component:login},
                // redirect进入页面的时候,直接就去login组件的页面
                { path: "/", redirect: "/login"}, // The second way to pass parameters {path:"/login/:id/:name", component: login },

                { path: "/register", Component: register}], // Default:"router-link-active"// Set the name of the CSS class to use when the link is activated. The default value can be configured globally with the route construction option linkActiveClass. // Change your style to the desired linkActiveClass:"myStyle"

        })
Copy the code
  • 3,routerIf the property name is the same, you can write it directly
// Register the routing rule object with the VM instance to listen for URL object address changes. // Router: router RouterCopy the code
  • Demo
<! 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>Document</title> <! -- vue --> <script src="https://unpkg.com/vue/dist/vue.js"></script> <! -- vue routing --> <script SRC ="https://unpkg.com/vue-router/dist/vue-router.js"Word-wrap: break-word! Important; "></script> <style> font-weight: 800; Font-size: 16px; /* size */ font-size: 100px; /* underline */ text-indent: underline; /* background-color: goldenrod}. MyStyle {color: hotpink; } .v-enter, .v-leaver-to { opacity: 0; transform: translateX(100px); }. V-enter-active,. V-leaver -active {transition: all 0.5s ease; } </style> </head> <body> <div id="app"> <! -- Not recommended --> <! -- <a href="#/login"</a> <a href="#/register"> Register </a> --> <! <router-link to=? <router-link to="/login/10/lishiming" tag="span"</router-link> <router-link to="/register"> Register </router-link> <! This is an element provided in vue-router for station use --> <! -- Wrap animation mode="out-in"<transition mode="out-in">< router-view></router-view> </transition> </div> <script>"<h1> I am login component {{$route.params.id}}----{{$route.params.name}}</h1>", // The component lifecyclecreated() {
                console.log("I'm logging in to the component.")
                console.log(this.$route.params.id)
            
            },
        }
        var register = {
            template: "< H1 > I am a registered component "} const router = new VueRouter({// // Component must be a component template object, not the name of the component application. // Specify that the default is login, // {path:"/",component:login},
                // redirect进入页面的时候,直接就去login组件的页面
                { path: "/", redirect: "/login"}, // The second way to pass parameters {path:"/login/:id/:name", component: login },

                { path: "/register", Component: register}], // Default:"router-link-active"// Set the name of the CSS class to use when the link is activated. The default value can be configured globally with the route construction option linkActiveClass. // Change your style to the desired linkActiveClass:"myStyle"

        })


        var vm = new Vue({
            el: "#app", data: {}, methods: {}, // Register the routing rule object on the VM instance, which is used to listen for the URL object address change. Router: router Router}) </script> </body> </ HTML >Copy the code
  • Nesting of routes
  • usechildrenProperty to implement the nesting of routes
  • usechildrenProperty to implement child routing, at the same time, the child routingpathDon’t bring it in front/If yes, the request will always start with the root path, which is not convenient for us users to understandURLaddress
  • <router-view></router-view>Placeholders must be used if use is required
  • Demo
<! 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>Document</title> <! -- vue --> <script src="https://unpkg.com/vue/dist/vue.js"></script> <! -- vue routing --> <script SRC ="https://unpkg.com/vue-router/dist/vue-router.js"></script>

</head>

<body>

    <div id="app"> <! This way you can reference components too --> <! -- <shiming></shiming> --> <router-link to="/acount">Acount</router-link>
        <router-view></router-view>

    </div>


    <template id="tmpl"> <div> <h1> This is the Account component and there is a route nested inside </h1> <! -- routing nesting --> <router-link to="/acount/login"</router-link> <router-link to="/acount/register"> Register </router-link> <! <router-view></router-view> </div> </template> <script> var account = {template:"#tmpl"
        }
        var login = {
            template: "< h3 > log in < / h3 >"
        }
        var register = {
            template: "< h3 > of < / h3 >"} const router = new VueRouter({//"/acount", component: account, // Use the children attribute to nest routes // Remember that login cannot be preceded by // / there are other ways, but what? Advised to such use, and easy to understand/use/children attribute, zi lu by, at the same time, zi lu by paht don't bring/front, if the belt, it always begins with a root request, it is not convenient to our users to understand the URL address children: [{path:"login", component: login },
                        { path: "register", component: register }
                    ]
                },
                // // 
                //  { path: "/acount/login", component: login },

                //  { path: "/acount/register", component: register }
            ]
        })
        var vm = new Vue({
            el: "#app",

            data: {

            },

            methods: {

            },
            components: {
                "shiming": account
            },
            router
        })
    </script>
</body>

</html>
Copy the code
  • Classic layout
  • componentsThere are many components
  • <router-view></router-view>Three pit
<! 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>Document</title> <! -- vue --> <script src="https://unpkg.com/vue/dist/vue.js"></script> <! -- vue routing --> <script SRC ="https://unpkg.com/vue-router/dist/vue-router.js"></script> <style> /* Set the body margin of the HTML page */ HTML,body{margin: 0; padding: 0; } .container { display: flex; } /* h1{margin: 0; padding: 0; font-size: 20px; } .header { background-color: aqua; height: 100px; } .left { background-color: yellow; flex: 2; height: 600px; } .main { background-color: blueviolet; flex: 10; height: 600px; } </style> </head> <body> <div id="app"> <! <router-view>< div class="container">

            <router-view name="left"></router-view>

            <router-view name="main"></router-view>
        </div>

    </div>

    <script>

        var header = {
            template: "

Header

"
} var leftBox = { template: "

left sidebar

} var mainBox = { template: "

mainBox

"
} const router = new VueRouter({routes: [//}) const router = new VueRouter({routes: [//})"/",component:header}, // {path:"/left",component:left}, // {path:"/mainBox",component:mainBox}, // components corresponds to many components {path:"/", components: { "default": header, "left": leftBox, "main": mainBox } } ] }) var vm = new Vue({ el: "#app"// Router}) </script> </body> </ HTML >Copy the code
  • Above, to be continued