不积跬步,无以至千里;不积小流,无以成江海。
Vuejs语言基础
父子组件通信——父传子:
通过 props 在父子组件传值,父组件中通过 v-bind:data="data",决定子组件中的 props 接收的到底是哪个。
1. 创建一个父组件 Parent.vue,在data中添加一个parentAge
<template>
<div class="my-parent">
<h3>我是父组件</h3>
<p>父组件的年龄是:{{parentAge}}</p>
</div>
</template>
<script>
export default {
data() {
return {
parentAge: 50
};
}
};
</script>
<style>
.my-parent {
text-align: left;
text-indent: 1em;
width: 1000px;
height: 500px;
border: 1px solid #555;
}
</style>
2. 创建子组件,在data中添加一个childAge
<template>
<div class="my-child">
<h3>我是子组件</h3>
<p>子组件的年龄是:{{childAge}}</p>
</div>
</template>
<script>
export default {
data() {
return {
childAge: 27
};
}
};
</script>
<style>
.my-child {
margin: 20px;
width: 760px;
height: 200px;
border: 1px solid red;
}
</style>
3. 把父子组件关联起来
通过v-bind(即简写“:”)将父组件中的 parentAge 值,传递给子组件;deliverParentAge通过v-bind绑定的,也是子组件中通过props接收的,而parentAge是要传递给子组件的数值(绑定的属性名称deliverParentAge与data中定义的parentAge名称可以不一样)
<template>
<div class="my-parent">
<h3>我是父组件,我想告诉我的子组件,我的年龄值是:{{parentAge}}</h3>
<h3>我要通过v-bind绑定一个属性deliverParentAge,将父组件的值传递到子组件中</h3>
<!-- 下面就是我的子组件 -->
<my-child :deliverParentAge="parentAge"></my-child>
</div>
</template>
<script>
import MyChild from "./Child";
export default {
components: { MyChild },
data() {
return {
parentAge: 49
};
}
};
</script>
4. 子组件通过 props 属性,在子组件中接收父组件传过来的值
<template>
<div class="my-child">
<h5>我是子组件,我可以通过属性props来接收父组件传过来的年龄值是:{{deliverParentAge}}</h5>
</div>
</template>
<script>
export default {
data() {
return {
childAge: 27
};
},
props: {
deliverParentAge: Number
}
};
</script>
Prop 验证
为组件的 prop 指定需求。如果有一个需求没有被满足,则 Vue 会在浏览器控制台中警告你。这在开发一个会被别人用到的组件时尤其有帮助。
为了定制 prop 的验证方式,你可以为 props 中的值提供一个带有验证需求的对象,而不是一个字符串数组。例如:
Vue.component('my-component', {
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 ['success', 'warning', 'danger'].indexOf(value) !== -1
}
}
}
})
浙公网安备 33010602011771号