Vue $props 对象
实例
使用 $props 对象来显示收到的 prop。
<template><div><h3>Received Props</h3><p>This is the $props object:</p><pre>{{ this.$props }}</pre></div></template>
定义与用法
$props 对象用当前值表示组件中声明的 prop。
Vue 中的 prop 是将值作为属性传递给子组件的一种方式。
$props 对象可以用于例如将 prop 进一步传递到下一个子组件(参见下面的实例1),或者例如基于 prop 设置计算属性(下面的实例2)。
$props 对象是只读的。
更多实例
实例 1
使用 $props 对象将props传递给下一个子组件。
<template><div><h3>InfoBox.vue</h3><p>This is the $props object that is received from App.vue and passed down to the next child component:</p><pre>{{ this.$props }}</pre><grand-child v-bind="$props" /></div></template><script>export default {props: ['bagOwner','bagWeight']}</script><style scoped>div {border: solid black 1px;padding: 10px;margin-top: 20px;max-width: 370px;}</style>
实例 2
使用计算属性中的 $props 对象根据袋子的重量创建反馈消息。
<template><div><h3>InfoBox.vue</h3><p>The $props object is used in a computed value to create a message based on the weight of the bag:</p><span>{{ this.bagWeightStatus }}</span></div></template><script>export default {props: ['bagWeight'],computed: {bagWeightStatus() {if(this.$props.bagWeight>10) {return 'Puh, this bag is heavy!'}else {return 'This bag is not so heavy.'}}}}</script><style scoped>div {border: solid black 1px;padding: 10px;max-width: 350px;margin-top: 20px;}span {background-color: lightgreen;padding: 5px 10px;font-weight: bold;}</style>