分享Vue子组件接收父组件传值的3种方式
Vue作为一款流行的前端框架,具有组件化以及数据驱动的特点,使得父子组件的通信十分方便,而在Vue中,父组件可以向子组件传递数据以及事件。以下是Vue子组件接收父组件传值的3种方式。
1. props
props是Vue中传递数据的常用方式,父组件可以通过props向子组件传递数据。子组件通过在组件对象中定义props选项来声明它将要接收哪些属性。
父组件中使用例子:
<template>
<div>
<ChildComponent :message="message" :number="number" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent'
export default {
components: {
ChildComponent
},
data() {
return {
message: 'hello world',
number: 123
}
}
}
</script>
子组件中使用例子:
<template>
<div>
<h1>{{ message }}</h1>
<p>{{ number }}</p>
</div>
</template>
<script>
export default {
props: {
message: String,
number: Number
}
}
</script>
2. $attrs、$listeners
在有些情况下,我们需要在子组件中访问父组件的事件和一些非prop属性。Vue提供了$attrs和$listeners选项来解决这个问题。
$attrs是父组件中绑定在组件上的非prop属性对象,子组件使用时需要通过v-bind="$attrs"将非prop属性传递给子组件。
$listeners是父组件中绑定在组件上的事件对象,子组件使用时需要通过v-on="$listeners"将事件传递给子组件。
父组件中使用例子:
<template>
<div>
<ChildComponent :message="message" @click="handleClick" name="John" />
</div>
</template>
<script>
import ChildComponent from './ChildComponent'
export default {
components: {
ChildComponent
},
data() {
return {
message: 'hello world',
}
},
methods: {
handleClick() {
console.log('clicked')
}
}
}
</script>
子组件中使用例子:
<template>
<div>
<h1>{{ message }}</h1>
<button @click="$emit('click', name)">Click</button>
</div>
</template>
<script>
export default {
inheritAttrs: false,
props: {
message: String
},
mounted() {
console.log(this.$attrs.name)
}
}
</script>
3. provide、inject
provide、inject是Vue2.2.0新增的特性,它们可以用于父子组件通信,但是它们不是响应式的,所以它们的使用需要注意。
父组件使用provide选项传递数据,子组件使用inject选项来注入数据。
父组件中使用例子:
<template>
<div>
<ChildComponent />
</div>
</template>
<script>
import ChildComponent from './ChildComponent'
export default {
components: {
ChildComponent
},
provide() {
return {
message: 'hello world'
}
}
}
</script>
子组件中使用例子:
<template>
<div>
<h1>{{ message }}</h1>
</div>
</template>
<script>
export default {
inject: ['message']
}
</script>
总结
以上是Vue子组件接收父组件传值的3种方式,每种方式都有其特点和使用场景。props是最常用的传值方式,用于传递父组件的数据给子组件;$attrs和$listeners则是用于传递父组件的非prop属性和事件给子组件;provide、inject则适用于组件通信场景,但是注意它们不是响应式的,需要慎重使用。大家根据自己项目的实际需要来选择合适的方法来进行父子组件的通信。
