vue组件Prop传递数据的实现示例
2017-08-17 10:11
876 查看
组件实例的作用域是孤立的。这意味着不能(也不应该)在子组件的模板内直接引用父组件的数据。要让子组件使用父组件的数据,我们需要通过子组件的props选项。
prop 是单向绑定的:当父组件的属性变化时,将传导给子组件,但是不会反过来。这是为了防止子组件无意修改了父组件的状态。
每次父组件更新时,子组件的所有 prop 都会更新为最新值。这意味着你不应该在子组件内部改变 prop。
1、Prop静态传递数据
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="vue.js"></script> </head> <body > <div id="app"> <!--静态传递数据--> <my-component message="hello" name="刘二狗" age="18"></my-component> </div> </body> <script> Vue.component('my-component',{ //子组件使用父组件的数据 message name age props:['message','name','age'], //用data选项对数据进行处理 data:function(){ return{ message1: this.message +'用data选项对数据进行处理' } }, //用计算属性选项对数据进行处理 computed:{ message2:function(){ return this.message + '用计算属性选项对数据进行处理' } }, template:'<div>' + '<span>{{message1}}</span><br>'+ '<span>{{message2}}</span><br>'+ '<span>{{message}} {{name}}今年{{age}}了</span><br>'+ '</div>' }) new Vue({ el:'#app' }) </script> </html>
输出结果:
2、Prop动态传递数据
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="vue.js"></script> </head> <body > <div id="app"> <input v-model="parentMsg"><br> <my-component :message="parentMsg"></my-component> </div> </body> <script> Vue.component('my-component',{ props:['message'], data:function(){ return{count:this.message+'刘三狗的嫉妒了'} }, computed:{ normalizedSize: function () { return this.message.trim().toLowerCase() } }, template:'<div>' + '<span>{{message}}---{{normalizedSize}}</span><br>'+ '<span>{{count}}</span>'+ '</div>' }) new Vue({ el:'#app', data:{ parentMsg:'哈哈哈' } }) </script> </html>
输出结果:
3、Prop验证,我们可以为组件的 props 指定验证规格。如果传入的数据不符合规格,Vue 会发出警告。在前台的控制器中可以看到警告信息。
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> <script type="text/javascript" src="vue.js"></script> </head> <body> <div id="app"> <example :prop-d="message"></example> </div> </body> <script> Vue.component('example', { props: { // 基础类型检测 (`null` 意思是任何类型都可以) propA: Number, // 多种类型 propB: [String, Number], // 必传且是字符串 propC: { type: String, required: true }, // 数字,有默认值 propD: { type: Number, default: 100 }, // 数组/对象的默认值应当由一个工厂函数返回 propE: { type: Object, default: function () { return { message: 'hello' } } }, // 自定义验证函数 propF: { validator: function (value) { return value > 10 } } }, template:'<span>{{propD}}</span>' }) new Vue({ el:'#app', data:{ message:'propD验证只能传入数字类型' } }) </script> </html>
控制台输出的警告信息:
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
您可能感兴趣的文章:
相关文章推荐
- Vue.js使用-组件示例(实现数据的CRUD)
- Vue2.0组件间数据传递示例
- Vue表单类的父子组件数据传递示例
- Vue中组件之间数据的传递的示例代码
- VUE快速入门新的——组件之间传递数据(1. Prop)
- vue组件(二)--prop传递数据
- vue中子组件向父组件传递数据的实例代码(实现加减功能)
- vue父子组件的数据传递示例
- vue.js中的子组件与父组件,prop传递数据
- vue中各组件之间传递数据的方法示例
- vue组件传递对象中实现单向绑定的示例
- vue.js 组件 之 prop 传递数据
- VUE实现一个分页组件的示例
- Vue.js实战之组件之间的数据传递
- Vue.js-----轻量高效的MVVM框架(九、组件利用Props传递数据)
- ReactJs实现树形结构的数据显示的组件的示例
- vue.js 学习之组件之间数据传递详解
- vue2.0父子组件间传递数据的方法
- Vue子父组件间的数据传递
- Vue模拟数据,实现路由进入商品详情页面的示例