Vue从入门到实战:使用Prop向子组件传递数据
来自CloudWiki
在使用组件时,给组件元素设置属性,组件内部如何接收呢 ?
首先需要在组件内部注册一些自定义的属性,称为prop
Vue.component('blog-post', { props: ['title'], template: '<h3>{{ title }}</h3>' })
之后,在使用组件时,就可以通过属性向组件传递数据:
<blog-post title="My journey with Vue"></blog-post> <blog-post title="Blogging with Vue"></blog-post> <blog-post title="Why Vue is so fun"></blog-post>
在字符串模板中,不必必须使用kebab-case命名法(短横线分割命名),各种命名可以直接使用。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <script src="vue.js"></script> </head> <body> <div id="app"> <post-list></post-list> </div> <script> Vue.component('PostItem', { // 声明props props: ['postTitle'], // postTitle就像data中定义的数据属性一样, // 在该组件中可以像 "this.postTitle" 这样使用 template: '<h3>{{ postTitle }}</h3>' }); Vue.component('PostList', { data() { return { title: 'Vue.js无难事' } }, // 在字符串模板中可以直接使用PascalCase命名的组件名 // 和camelCase命名的prop名 template: '<div><PostItem :postTitle="title"></PostItem></div>' }); new Vue({ el: '#app' }) </script> </body> </html>