在Vue中,组件之间传递参数常用的方法有以下几种:
父组件向子组件传递参数
父组件向子组件传递参数可以通过props属性实现,父组件将需要传递的参数作为props属性的值传递给子组件,子组件通过props接收该参数。例如:
父组件:
<template>
<child-component :name="name"></child-component>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
name: 'Tom'
}
}
}
</script>
子组件:
<template>
<div>姓名:{{ name }}</div>
</template>
<script>
export default {
props: {
name: {
type: String,
required: true
}
}
}
</script>
子组件向父组件传递参数
子组件向父组件传递参数可以通过自定义事件实现,子组件通过$emit方法触发一个自定义事件,传递需要传递的参数,父组件通过在子组件上绑定自定义事件实现接收参数。例如:
父组件:
<template>
<child-component @age-change="onAgeChange"></child-component>
<div>年龄:{{ age }}</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
components: {
ChildComponent
},
data() {
return {
age: 18
}
},
methods: {
onAgeChange(newAge) {
this.age = newAge;
}
}
}
</script>
子组件:
<template>
<div>
<button @click="changeAge">改变年龄</button>
</div>
</template>
<script>
export default {
methods: {
changeAge() {
this.$emit('age-change', 20);
}
}
}
</script>
以上是两种最常用的Vue组件间传递参数的方法,还有其他的传递参数的方式,如路由传参、Vuex传参等。