一、父组件->子组件 通过props
1、子组件:
声明:proprs =[‘xx’],xx是在父组件中引用子组件,子组件的属性(template)
引用:{{xx}}
2、父组件
声明数据:oo
父组件template中引用子组件,属性的值为oo
记忆:父->子 传值,父要有值
a、传递字符串
<!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> </head> <body> <div id="app"> <!-- <button>{{msg}}</button> --> </div> <script src="./js/vue.js"></script> <script> // Vue(父)->App(子) //1. 声明子组件 let App = { data(){ return { text:"咬我", } }, // b.使用声明的变量 template: ` <div> <p>{{text}}</p> <h4>{{abc}}</h4> </div> `, // a.声明props props:['abc'], } new Vue({ el: "#app", data(){ // c.声明值 return { msg: "点我", } }, // 若 Vue对象有template,则template优先级高 // 3.引用子组件 // d.在父组件中声明,子组件的属性和值 template: ` <div> <button>{{msg}}</button> <App :abc="msg"></App> </div> `, // 2.挂载子组件 components:{ App, } }) </script> </body> </html>
b、传递对象
<!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> </head> <body> <div id="app"> </div> <script src="./js/vue.js"></script> <script> let App = { data(){ return { msg: "Vue" } }, // 2. template: ` <p>{{mpost.title}}</p> `, // 1. props: ['mpost'] } new Vue({ el: "#app", data(){ return { // 3 post: { id: 1, title: 'My Journey with Vue' } } }, template: ` <div> <App :mpost="post"></App> </div>`, components:{ App, }, }) </script> </body> </html>
或
<!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> </head> <body> <div id="app"> </div> <script src="./js/vue.js"></script> <script> let App = { data(){ return { msg: "Vue" } }, // 2. template: ` <p>{{id}}</p> `, // 1. props: ['id', "title"] } new Vue({ el: "#app", data(){ return { // 3 post: { id: 1, title: 'My Journey with Vue' } } }, template: ` <div> <App :id="post.id" :title="post.title"></App> </div>`, components:{ App, }, }) </script> </body> </html>