父组件给子组件传值基本用法
-
组件内通过
props
接收传递过来的值Vue.component('small-item', { props: ['title', ], data: function() { return { msg: '子组件数据' } }, template: '<div>{{msg + "---" + title}}</div>', });
-
父组件通过属性将值传递给子组件
-
传递静态数据
<div id="app"> <!-- 传入静态数据 --> <small-item title="子组件参数的值"></small-item> </div>
Vue.component('small-item', { props: ['title', ], data: function() { return { msg: '子组件数据' } }, template: '<div>{{msg + "---" + title}}</div>', });
-
传递动态数据
<div id="app"> <!-- 传入动态数据 --> <small-item :title="con"></small-item> </div>
Vue.component('small-item', { props: ['title', ], data: function() { return { msg: '子组件数据' } }, template: '<div>{{msg + "---" + title}}</div>', }); // 实例化一个Vue对象,这个对象相当于是一个组件 var vm = new Vue({ el: '#app', data: { con: '父组件传给子组件的值' }, methods: {} });
Vue对象相当于是一个组件
-
-
props
属性命名规则-
在
props
中使用驼峰形式,模板(html
)中需要使用短横线的形式<small-item small-item="hello"></small-item>
Vue.component('small-item', { props: ['smallItem', ], data: function() { return { msg: '子组件数据' } }, template: '<div>{{msg + "---" + smallItem}}</div>', });
-
在字符串形式的模板中没有这个限制
<small-item small-item="hello"></small-item>
Vue.component('big-item', { props: ['bigItem', ], data: function() { return { msg: 'big子组件数据' } }, template: '<div>{{msg + "---" + bigItem}}</div>', }); Vue.component('small-item', { props: ['smallItem', ], data: function() { return { msg: '子组件数据' } }, template: '<div>{{msg + "---" + smallItem}}<big-item bigItem="nihao"></big-item></div>', });
-
-
props
属性值类型-
字符串
String
<small-item small-item="hello"></small-item>
-
数值
Number
<small-item :small-item="12"></small-item>
需要
bind
绑定 -
布尔值
Boolean
<small-item small-item="true"></small-item>
-
数组
Array
<small-item small-item="['apple', 'orange', 'banana']"></small-item>
-
对象
Object
<small-item small-item="{name: 'zhangsan', age: '18'}"></small-item>
-