Vue.js组件使用props传递数据的方法

通常父组件的模板中包含子组件,父组件要正向地向子组件传递数据或参数,子组件接收到后根据参数的不同来渲染不同的内容或执行操作。这个正向传递数据的过程就是通过props来实现的。

在组件中,使用选项props来声明需要从父级接收的数据,props的值可以是两种,一种是字符串数组,一种是对象。

示例:构造一个数组,接收一个来自父组件的message,并把它再组件模板中渲染

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="https://unpkg.com/vue/dist/vue.js"></script> <title>props</title> </head> <body> <div> <my-component message="来自父组件的数据"></my-component> </div> <script> Vue.component('my-component',{ props: ['message'], template: '<div>{{message}}</div>' }); var myApp = new Vue({ el: '#myApp' }); </script> </body> </html>

props中声明的数据与组件函数return的数据主要区别是:**props的数据来自父级,而data中的数据是组件自己的数据,作用域是组件本身。**这两种数据都可以在模板template及计算属性computed和方法methods中使用。

上例的数据message就是通过props从父级传递过来的,在组件的字的那个一标签上直接写该props的名称,如果要传递多个数据,在props数组中添加项即可。

注意:由于HTML特性不区分大小写,当使用DOM模板时,驼峰命名的props名称要转为短横分割命名,例如:

<div> <my-component warning-text="提示信息"></my-component> </div> <script> //如果使用字符串模板,可以忽略这些限制 Vue.component('my-component',{ props: ['warningText'], template: '<div>{{warningText}}</div>' }); var app = new Vue({ el: '#app' }); </script>

有时候,传递的数据并不是直接写死的,而是来自父级的动态数据,这时候可以使用指令v-bing来动态绑定props的值,当父组件的数据变化时,也会传递给子组件。

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="https://unpkg.com/vue/dist/vue.js"></script> <title>动态绑定</title> </head> <body> <div> <input type="text" v-model="parentMessage"> <my-component :message="parentMessage"></my-component> </div> <script> Vue.component('my-component',{ props: ['message'], template: '<div>{{message}}</div>' }); var app = new Vue({ el: '#app', data: { parentMessage: '' } }); </script> </body> </html>

Vue.js组件使用props传递数据的方法

上例使用v-model绑定了父级的数据parentMessage,当通过输入框任意输入时,子组件接受到的props "message"也会实时响应,并更新组件模板。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/878c5d91db6d050634df28cd8e33e022.html