父=>子 组件传参
设置props属性就可以接受父组件传值
data和props的区别
- data是组件私有的,props是父组件传过来的
- data是可以修改的,props是只读的
<body>
<div id='app'>
<parent></parent>
</div>
<!-- 父模板 -->
<template id="parent">
<!--属性名:自定义 属性值:要接收的父组件的变量名-->
<child :parent_cars="carList"></child>
</template>
<!-- 子模板 -->
<template id="child">
<ul>
<li v-for="(item,index) in parent_cars" :key="item.id">
{
{item.name}}--------{
{item.price}}
</li>
</ul>
</template>
<script>
Vue.component('parent', {
template: '#parent',
data() {
return {
carList: [
{
id: 1,name: '1car',price: '11¥'},
{
id: 2,name: '2car',price: '22¥'},
{
id: 3,name: '3car',price: '33¥'}
]
}
}
})
Vue.component('child', {
template: '#child',
// 定义父组件传过来的值
props: {
//设置类型 可以设置多个类型,可以传Number也可以传String
// 属性名要和自定义的属性名相同 ----<child :parent_cars="carList"></child>
parent_cars: [Array],
// 设置默认值的时候必须使用函数,原理和data必须使用函数是一样的
default: function () {
return [{
name: '这个一个默认的名字'}]
}
}
})
const vm = new Vue({
el: '#app',
data: {
},
methods: {
}
})
</script>
</body>