组件间如何传值
序言
关于组件之间值得传递我了解甚微,只知道普通的在跳转页面时触发传递值事件,后面经过学习熟悉了父与子组件之间的传递以及兄弟组件之间的传递,今天我们着重了解父与子组件之间传值
普通传值
例如:
uni.navigateTo({
url: "/otherpages/pages/bookingAdmission/bookingSuccess?param=" +
JSON.stringify(param)})
在跳转页面的时候把param转换成的JSON字符串传递到/otherpages/pages/bookingAdmission/bookingSuccess页面,在这个页面能够直接从onload方法中获取
onload(option){
console.log(option)
}
能够发现此时打印出来的值就是上一个页面传来的值
父与子组件之间的传递
父组件需要向子组件传递数据时,可以通过 props 属性进行传递。
父组件:
<template>
<div>
<child-component :dataProp="parentData"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
data() {
return {
parentData: 'Hello from parent',
};
},
components: {
ChildComponent
}
}
</script>
子组件
<template>
<div>
<p>{{ dataProp }}</p>
</div>
</template>
<script>
export default {
props: ['dataProp']
}
</script>
父组件通过将数据 parentData 通过 props 属性传递给子组件 ChildComponent。子组件通过声明 props: [‘dataProp’] 来接收父组件传递的数据,并在模板中使用 dataProp 来展示。
其中:dataProp 是一个占位符,您可以随意定义它的名称,比如 :label、:value 等等。
子组件向父组件进行传值通过this.$emit实现
子组件
<!-- 子组件 ChildComponent.vue -->
<template>
<div>
<button @click="sendData">Send Data</button>
</div>
</template>
<script>
export default {
methods: {
sendData() {
this.$emit('data-emitted', 'Hello from ChildComponent');
},
},
};
</script>
父组件
<!-- 父组件 ParentComponent.vue -->
<template>
<div>
<p>{{ receivedData }}</p>
<child-component @data-emitted="handleData"></child-component>
</div>
</template>
<script>
import ChildComponent from './ChildComponent.vue';
export default {
data() {
return {
receivedData: '',
};
},
methods: {
handleData(data) {
this.receivedData = data;
},
},
components: {
ChildComponent,
},
};
</script>
子组件在按钮的点击事件中触发了一个名为 data-emitted 的自定义事件,并传递了数据 ‘Hello from ChildComponent’。在父组件中,通过监听子组件的 data-emitted 事件,并在事件回调函数 handleData 中接收传递的数据,并将其赋值给 receivedData 数据,然后在模板中显示出来。
其中:data-emitted 是一个自定义事件的名称,可以根据自己的需求,随意定义自定义事件的名称,
结尾
以上就是普通传值及父与子组件之间传值的方式, 感谢大家观看