Vue 2 父子组件传值有如下几种方式:props(自上而下):父组件通过 props 传值给子组件。$emit(自下而上):子组件通过 $emit 事件向父组件发送数据。provide/inject(隐式父子通信):父组件提供值,子组件注入该值。Vuex(状态管理):父子组件共享 Vuex 中的数据。ref(模板引用):父组件通过 ref 获取子组件实例。

Vue 2 父子组件传值方式
Vue 2 中父子组件传值有多种方式,包括:
1. props(自上而下)
2. $emit(自下而上)
立即学习“前端免费学习笔记(深入)”;
3. provide/inject(隐式父子通信)
4. Vuex(状态管理)
5. ref(模板引用)
选择合适的方式
选择合适的传值方式取决于具体的场景和数据类型:
示例
props(父组件)
<code class="html"><template>
<child-component :message="message" />
</template>
<script>
export default {
data() {
return {
message: 'Hello from parent!'
}
}
}
</script></code>props(子组件)
<code class="html"><template>
<p>{{ message }}</p>
</template>
<script>
export default {
props: ['message']
}
</script></code>$emit(子组件)
<code class="html"><template>
<button @click="emitData">Send Data</button>
</template>
<script>
export default {
methods: {
emitData() {
this.$emit('sendData', { name: 'John' })
}
}
}
</script></code>$emit(父组件)
<code class="html"><template>
<child-component @sendData="receiveData"></child-component>
</template>
<script>
export default {
methods: {
receiveData(data) {
console.log(data)
}
}
}
</script></code>以上就是vue2父子组件传值有哪些的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号