Parent component passes value to child component
- Component instance definition method, note: be sure to use
props
Property to define the data passed by the parent component:
<script>
var vm=new Vue({
el:'#app',
data () {
return{
msg:'This is a message from the parent component'}},methods:{
},
components: {son: {template:' This is a child component -- {{finfo}}
'.props: ['finfo']}}});</script>
Copy the code
- use
v-bind
Or simplify instructions to pass data to child components:
<div id="app">
<son :finfo="msg"></son>
</div>
Copy the code
The code examples
<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='https://cdn.bootcss.com/vue/2.6.10/vue.min.js'></script>
</head>
<body>
<div id="app">
<! When the parent can reference the child, v-bind the data we need to pass to the child to be used by the child.
<com1 v-bind:parentmsg="msg"></com1>
</div>
<script>
var vm = new Vue({
el: '#app',
data() {
// The data in the child component is not passed by the parent component, but is private to the child component
// Data is readable and writable
return {
msg: '123 ah - data in parent component '
}
},
methods: {
},
components: {
// Conclusion: By default, the child component cannot access the data in the parent component and the methods in the parent component
com1: {
template: '< h1 @ click = "change" > this is child components - {{parentmsg}} < / h1 >'.// Note that all data in the component is passed from the parent component to the child component
// The props data is read-only and cannot be reassigned
props: ['parentmsg'].// Define the parentmsg property passed by the parent component in the props array so that this data can be used
methods:{
change(){
this.parentmsg = "Modified."}}}},});</script>
</body>
</html>
Copy the code
The parent component passes methods to the children and brings the values in the children back to the parent
The code examples
<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='https://cdn.bootcss.com/vue/2.6.10/vue.min.js'></script>
</head>
<body>
<div id="app">
<! The parent component passes the method to the child component using the event binding mechanism V-ON. When we define an event attribute, the child component can somehow call the method passed in.
<com2 @func="show"></com2>
</div>
<template id="tmp1">
<div>
<h1>This is the child component</h1>
<input type="button" value="Here's the button on the child component, click on it to trigger the func method passed by the parent component." @click="myclick">
</div>
</template>
<script>
// Defines a component template type of literal type
let com2 = {
template:'#tmp1'.// Specify an Id to load the contents of the template element as the component's HTML structure
data(){
return {
sonmsg: {name:'Little head son'.age: 6}}},methods:{
myclick(){
// How do I get the func method passed by the parent component and call it when I click the button of the child component?
// Emit; emit; emit; emit
this.$emit('func'.this.sonmsg)
}
}
}
var vm=new Vue({
el:'#app',
data () {
return{
datamsgFormSon:null}},methods:{
show(data){
console.log("Called show method on parent component :--" + data)
this.datamsgFormSon = data
}
},
components:{
com2
}
});
</script>
</body>
</html>
Copy the code
Build case – Comment list
<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='https://cdn.bootcss.com/vue/2.6.10/vue.min.js'></script>
<link href="https://cdn.bootcss.com/twitter-bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div id="app">
<cmt-box @func="loadComments"></cmt-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="tmp1">
<div>
<div class="form-group">
<label>Comment on:</label>
<input type="text" class="form-control" v-model="user">
</div>
<div class="form-group">
<label>Comments:</label>
<textarea class="form-control" v-model="content"></textarea>
</div>
<div class="form-group">
<input type="button" value="Comment" class="btn btn-primary" @click="postComment">
</div>
</div>
</template>
<script>
let commentBox = {
template: '#tmp1',
data(){
return {
user:' '.content:' ',}},methods:{
postComment(){// How to make a comment
// Analysis: business logic for Posting comments
//1. Where is the comment data stored?? Saved to localStorage
//2. Organize an updated comment data object
//3. Try to save the comment object obtained in step 2 to localStorage
// 3.1 localStorage only supports string data, call json.stringify first
Before saving the latest comment data, obtain the previous comment data from localStorage (string),
// Convert to an array object and push the latest comment into the array
// 3.3 If the comment string in localStorage is empty and does not exist, return a '[]' for json.parse to convert
// 3.4 Convert the latest comment list array to the array string again by calling json.stringify and then calling localstorage.setitem ()
// this.list.push()
let comment = {id:Date.now, user:this.user, content:this.content}
// Get all comments from localStorage
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')}}}var vm = new Vue({
el: '#app',
data() {
return {
list: [{id: Date.now(), user: '李白'.content: 'I was born to be useful.' },
{ id: Date.now(), user: 'Jiang Xiao Bai'.content: 'I urge you to drink more.' },
{ id: Date.now(), user: '小马'.content: 'My name is Ma. I'm a horse of cattle and sheep.'}}},],methods: {
loadComments(){// Load the comment list from the local localStorage
let list = JSON.parse(localStorage.getItem('cmts') | |'[]')
this.list = list
}
},
components: {
'cmt-box': commentBox
},
created() {
this.loadComments()
},
});
</script>
</body>
</html>
Copy the code
The final result
usethis.$refs
To get elements and components
You can invoke properties and methods in child components directly using this.$refs
<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='https://cdn.bootcss.com/vue/2.6.10/vue.min.js'></script>
</head>
<body>
<div id="app">
<input type="button" value="Get elements" @click="getElement" ref="btn">
<h3 ref='myh3'>Hahaha, what a beautiful day today!!</h3>
<hr>
<login ref="mylogin"></login>
</div>
<script>
var login = {
template: ' Login component
',
data(){
return {
msg:'son msg'}},methods:{
show(){
console.log('Called a child component's method')}}}var vm = new Vue({
el: '#app',
data() {
return{}},methods: {
getElement() {
// ref is the English word reference value type and the reference type referenceError
// console.log(this.$refs.myh3.innerText)
// console.log(this.$refs.mylogin.msg)
this.$refs.mylogin.show()
}
},
components: {
login
}
});
</script>
</body>
</html>
Copy the code
What is routing
- Back-end routing: For common websites, all hyperlinks are URLS, and all urls correspond to the corresponding resources on the server.
- Front-end routing: For single-page applications, the hash (#) in the URL is used to switch between different pages. The hash feature is that HTTP requests do not contain hash content. Therefore, the page jump in the single-page program is mainly implemented with hash.
- In single-page applications, this way of switching pages with hash changes is called front-end routing (as opposed to back-end routing);
Use vue-router in Vue
- Import vue-Router component class library
<script src="https://cdn.bootcss.com/vue-router/3.1.3/vue-router.min.js"></script>
Copy the code
- Use the router-link component to navigate
<! -- Router-link is rendered as an A tag by default, Use tag to change the default render tag --> <router-link to="/login"> Login </router-link> <router-link to="/register"> Register </router-link>Copy the code
- Use the router-view component to display matched components
<! This element is provided by vue-Router as a placeholder for components to be displayed on the vue-Router in the future, so we can consider it as a placeholder.
<router-view></router-view>
Copy the code
- Create a use
VueRouter
Create components
// Create a route object. After importing vue-Router, there is a route constructor called VueRouter in the window global object
// In the new route object, can be
const routerObj = new VueRouter({
//route The route in this configuration object stands for route matching rule
routes: [// Route matching rule
// Each route is an object, a rule object, with the necessary attributes
// Attribute 1 is path, indicating which route connection address to listen for
// Attribute 2 is Component, which shows the component of the component attribute if the route matches the path previously
// Note: The component property value must be a component template object, not the property name
{ path: "/login".component: login },
{ path: "/register".component: register },
]
})
var vm = new Vue({
el: '#app',
data() {
return{}},methods: {},router:routerObj// Register the routing rule object on our VM instance to listen for URL changes and display the corresponding components
});
Copy the code
Code example to implement route default highlighting
<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='https://cdn.bootcss.com/vue/2.6.10/vue.min.js'></script>
<! Install vue-router routing module -->
<script src="https://cdn.bootcss.com/vue-router/3.1.3/vue-router.min.js"></script>
<style>
.router-link-active..myactive{
color: red;
font-weight: 800;
font-style: ittalic;
font-size: 80px;
text-decoration: underline;
background-color: green;
}
</style>
</head>
<body>
<div id="app">
<! - < a href = "# / login" > login < / a > < a href = "# / register" > register < / a > -- >
<! -- Router-link renders to an A tag by default. You can use tag to change the default render tag.
<router-link to="/login">The login</router-link>
<router-link to="/register">registered</router-link>
<! This element is provided by vue-Router as a placeholder for components to be displayed on the vue-Router in the future, so we can consider it as a placeholder.
<router-view></router-view>
</div>
<script>
let login = {
template: ' Login component
'
}
let register = {
template: ' Registered Component
'
}
// Create a route object. After importing vue-Router, there is a route constructor called VueRouter in the window global object
// In the new route object, can be
const routerObj = new VueRouter({
//route The route in this configuration object stands for route matching rule
routes: [// Route matching rule
// Each route is an object, a rule object, with the necessary attributes
// Attribute 1 is path, indicating which route connection address to listen for
// Attribute 2 is Component, which shows the component of the component attribute if the route matches the path previously
// Note: The component property value must be a component template object, not the property name
{ path: "/".redirect:'/login' },Redirect and Redirect in Node are completely different things
{ path: "/login".component: login },
{ path: "/register".component: register },
],
linkActiveClass:'myactive'
})
var vm = new Vue({
el: '#app',
data() {
return{}},methods: {},router:routerObj// Register the routing rule object on our VM instance to listen for URL changes and display the corresponding components
});
</script>
</body>
</html>
Copy the code
Add a toggle animation for the route
- use
transition
The parcelrouter-view
The label
<transition mode="out in">
<router-view></router-view>
</transition>
Copy the code
- Define fixed animation styles
.v-enter..v-leave-to {
opacity: 0;
transform: translateX(140px);
}
.v-enter-active..v-laeve-active {
transition: all 0.5 s ease;
}
Copy the code
Parameter transfer is realized in routing rules
Method 1: Usequery
To get the parameters
<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='https://cdn.bootcss.com/vue/2.6.10/vue.min.js'></script>
<script src="https://cdn.bootcss.com/vue-router/3.1.3/vue-router.min.js"></script>
</head>
<body>
<div id="app">
<! -- If you use a query string to pass parameters to a route, you do not need to modify the path attribute of the routing rule -->
<router-link to="/login? =10&name=zs">The login</router-link>
<router-link to="/register">registered</router-link>
<router-view></router-view>
</div>
<script>
let login = {
template: '< h1 > login - {{$route. Query. Id}} - {{$route. The query. The name}} < / h1 >',
created() {// The component's lifecycle hook function
console.log(this.$route.query.id)
},
data(){
return{
id : this.$route.query.id
}
}
}
let register = {
template: '< h1 > register < / h1 >'
}
let router = new VueRouter({
routes: [{path: '/login'.component: login },
{ path: '/register'.component: register }
]
})
var vm = new Vue({
el: '#app',
data() {
return{}},methods: {
},
router
});
</script>
</body>
</html>
Copy the code
Method 2: Useparams
To get the data
<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='https://cdn.bootcss.com/vue/2.6.10/vue.min.js'></script>
<script src="https://cdn.bootcss.com/vue-router/3.1.3/vue-router.min.js"></script>
</head>
<body>
<div id="app">
<! -- If you use a query string to pass parameters to a route, you do not need to modify the path attribute of the routing rule -->
<router-link to="/login/10/lisi">The login</router-link>
<router-link to="/register">registered</router-link>
<router-view></router-view>
</div>
<script>
let login = {
template: '< h1 > login - {{this. $route. Params. Id}} - {{this. $route. Params. Name}} < / h1 >',
created() {// The component's lifecycle hook function
console.log(this.$route)
},
data(){
return{
// id : this.$route}}}let register = {
template: '< h1 > register < / h1 >'
}
let router = new VueRouter({
routes: [{path: '/login/:id/:name'.component: login },
{ path: '/register'.component: register }
]
})
var vm = new Vue({
el: '#app',
data() {
return{}},methods: {
},
router
});
</script>
</body>
</html>
Copy the code
Nesting of routes
It is possible that we need to nest other routes within a route in a requirement, in which case we need to use children to nest rules
<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='https://cdn.bootcss.com/vue/2.6.10/vue.min.js'></script>
<script src="https://cdn.bootcss.com/vue-router/3.1.3/vue-router.min.js"></script>
</head>
<body>
<div id="app">
<router-link to="/account">Account</router-link>
<router-view></router-view>
</div>
<template id="tmp1">
<div>
<h1>This is the Account component</h1>
<router-link to="/account/login">The login</router-link>
<router-link to="/account/register">registered</router-link>
<router-view></router-view>
</div>
</template>
<template id="tmp2">
<div>
<h3>This is the login component</h3>
</div>
</template>
<template id="tmp3">
<div>
<h3>This is the registration component</h3>
</div>
</template>
<script>
// The template object of the component
let account = {
template: "#tmp1"
}
let login = {
template: "#tmp2"
}
let register = {
template: "#tmp3"
}
const router = new VueRouter({
routes: [{path: '/account'.component: account,
// Use children to implement child routing without/before path,
// Otherwise, always start the request with the root path, which is inconvenient for us users to understand the URL address
children: [
{ path: 'login'.component: login },
{ path: 'register'.component: register },
]
},
// { path: '/account/login', component: login },
// { path: '/account/register', component: register },]})var vm = new Vue({
el: '#app',
data() {
return{}},methods: {
},
router
});
</script>
</body>
</html>
Copy the code
Named views implement a classic layout
<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='https://cdn.bootcss.com/vue/2.6.10/vue.min.js'></script>
<script src="https://cdn.bootcss.com/vue-router/3.1.3/vue-router.min.js"></script>
<style>
html.body{
margin: 0;
padding: 0;
}
.header{
background-color: orange;
height: 80px;
}
.left{
background-color: lightgreen;
flex:2
}
.main{
background-color: lightpink;
flex:8
}
h1{
margin: 0;
padding: 0;
font-size: 16px;
}
.container{
display: flex;
height: 600px;
}
</style>
</head>
<body>
<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: 'Header header
'
}
let leftBox = {
template: ' left header
}
let mainBox = {
template: ' main header
'
}
// Create a routing object
const router = new VueRouter({
routes: [
// {path:'/', component:header},
// {path:'/left', component:leftBox},
// {path:'/main', component:mainBox},
{ path: '/'.components: {
'default':header,
'left':leftBox,
'main':mainBox
}
},
]
})
var vm = new Vue({
el: '#app',
data() {
return{}},methods: {
},
router
});
</script>
</body>
</html>
Copy the code