Vue 子组件数据独立于父组件,只能访问通过 props 传递的数据。父组件使用 v-bind 指令和 props 选项向子组件传递数据。子组件使用 $attrs 访问除 props 声明外的父组件属性。子组件通过自定义事件向父组件传递数据。
Vue 子组件数据使用
在 Vue.js 中,子组件的数据与父组件的数据是分开的。子组件只能访问父组件通过 props 属性传递给它的数据。父组件可以通过 v-bind 指令向子组件传递数据。
使用 Props 传递数据
在子组件中,使用 props 选项指定需要接收的数据:
立即学习“前端免费学习笔记(深入)”;
export default { props: ['data'] };
在父组件中,使用 v-bind 指令传递数据:
<template> <ChildComponent v-bind:data="myData"></ChildComponent> </template> <script> export default { data() { return { myData: 'Hello Vue!' } } }; </script>
使用 $attrs 访问额外属性
除了 props 之外,子组件还可以通过 $attrs 访问父组件传递的其他属性,这些属性没有在 props 中显式声明。
在子组件中:
export default { mounted() { console.log(this.$attrs.extraAttribute); } };
在父组件中:
<template> <ChildComponent v-bind:data="myData" extra-attribute="foo"></ChildComponent> </template>
使用自定义事件
如果子组件需要向父组件传递数据,可以使用自定义事件。
在子组件中:
export default { methods: { emitData() { this.$emit('update-data', 'New data'); } } };
在父组件中:
<template> <ChildComponent @update-data="handleData"></ChildComponent> </template> <script> export default { methods: { handleData(newData) { // 处理新数据 } } }; </script>
以上就是vue子组件数据怎么用的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号