Vue组件通信之props深入详解!
props 是 Vue 组件中一个很重要的概念。它是用来从父组件向子组件传递数据的。为什么需要props?这是因为在Vue中,组件是相互隔离的。每个组件都有自己的作用域,子组件无法直接访问父组件的状态或值。通过props,父组件可以将数据传递给子组件。
使用props的步骤:
1. 在子组件中定义props选项,指定你希望从父组件接收的数据:
props: ['msg']
2. 在使用子组件的地方,使用v-bind或简写:来绑定父组件的数据到子组件的props:
<child :msg="parentMsg"></child>
3. 在子组件中,就像访问data中的值一样访问props中的值:
props: ['msg']
template: '<p>{{ msg }}</p>'
示例代码:
父组件:
<template>
<div>
<input v-model="parentMsg">
<child :msg="parentMsg"></child>
</div>
</template>
<script>
import Child from './Child.vue'
export default {
components: { Child },
data() {
return {
parentMsg: 'Hello from parent!'
}
}
}
</script>
子组件:
<template>
<p>{{ msg }}</p>
</template>
<script>
export default {
props: ['msg']
}
</script>
结果:
Hello from parent!
输入parentMsg的值改为"Hello from props!", 结果也会相应变为:
Hello from props!
这达到了通过props在父子组件间传递数据的效果。