vue组件 Prop传递数据
组件实例的作用域是孤立的。这意味着不能(也不应该)在子组件的模板内直接引用父组件的数据。要让子组件使用父组件的数据,我们需要通过子组件的props选项。
prop 是单向绑定的:当父组件的属性变化时,将传导给子组件,但是不会反过来。这是为了防止子组件无意修改了父组件的状态。
每次父组件更新时,子组件的所有 prop 都会更新为最新值。这意味着你不应该在子组件内部改变 prop。
1、Prop静态传递数据
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script type="text/javascript" src="vue.js"></script> 7 8 </head> 9 <body > 10 <div id="app"> 11 <!--静态传递数据--> 12 <my-component message="hello" name="刘二狗" age="18"></my-component> 13 </div> 14 </body> 15 16 <script> 17 Vue.component('my-component',{ 18 //子组件使用父组件的数据 message name age 19 props:['message','name','age'], 20 //用data选项对数据进行处理 21 data:function(){ 22 return{ 23 message1: this.message +'用data选项对数据进行处理' 24 } 25 }, 26 //用计算属性选项对数据进行处理 27 computed:{ 28 message2:function(){ 29 return this.message + '用计算属性选项对数据进行处理' 30 } 31 }, 32 template:'<div>' + 33 '<span>{{message1}}</span><br>'+ 34 '<span>{{message2}}</span><br>'+ 35 '<span>{{message}} {{name}}今年{{age}}了</span><br>'+ 36 '</div>' 37 }) 38 new Vue({ 39 el:'#app' 40 }) 41 </script> 42 </html>
输出结果:
2、Prop动态传递数据
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script type="text/javascript" src="vue.js"></script> 7 </head> 8 <body > 9 <div id="app"> 10 <input v-model="parentMsg"><br> 11 <my-component :message="parentMsg"></my-component> 12 </div> 13 </body> 14 15 <script> 16 Vue.component('my-component',{ 17 props:['message'], 18 data:function(){ 19 return{count:this.message+'刘三狗的嫉妒了'} 20 }, 21 computed:{ 22 normalizedSize: function () { 23 return this.message.trim().toLowerCase() 24 } 25 }, 26 template:'<div>' + 27 '<span>{{message}}---{{normalizedSize}}</span><br>'+ 28 '<span>{{count}}</span>'+ 29 '</div>' 30 }) 31 32 new Vue({ 33 el:'#app', 34 data:{ 35 parentMsg:'哈哈哈' 36 } 37 }) 38 </script> 39 </html>
输出结果:
3、Prop验证,我们可以为组件的 props 指定验证规格。如果传入的数据不符合规格,Vue 会发出警告。在前台的控制器中可以看到警告信息。
1 <!DOCTYPE html> 2 <html> 3 <head lang="en"> 4 <meta charset="UTF-8"> 5 <title></title> 6 <script type="text/javascript" src="vue.js"></script> 7 </head> 8 <body> 9 <div id="app"> 10 <example :prop-d="message"></example> 11 </div> 12 </body> 13 14 <script> 15 Vue.component('example', { 16 props: { 17 // 基础类型检测 (`null` 意思是任何类型都可以) 18 propA: Number, 19 // 多种类型 20 propB: [String, Number], 21 // 必传且是字符串 22 propC: { 23 type: String, 24 required: true 25 }, 26 // 数字,有默认值 27 propD: { 28 type: Number, 29 default: 100 30 }, 31 // 数组/对象的默认值应当由一个工厂函数返回 32 propE: { 33 type: Object, 34 default: function () { 35 return { message: 'hello' } 36 } 37 }, 38 // 自定义验证函数 39 propF: { 40 validator: function (value) { 41 return value > 10 42 } 43 } 44 }, 45 template:'<span>{{propD}}</span>' 46 }) 47 48 new Vue({ 49 el:'#app', 50 data:{ 51 message:'propD验证只能传入数字类型' 52 } 53 }) 54 </script> 55 </html>
控制台输出的警告信息: