vue的ref
$refs
尽管有props和events,但是仍然需要在JavaScript中直接访问子组件。
为此可以使用ref
为子组件指定一个索引ID。
注意,ref并不是动态更新的,也就是说不应该绑定变量,而是写一个固定值即可。
在home.vue
中添加list组件
<div class="home"> <list ref="childList"></list> <button @click="getChild()">获取子组件</button> </div>
home.vue
中的的方法中,可以直接访问到子组件对象
import List from '../components/list' export default { components: { List }, methods: { getChild() { // 获取子组件中的数据 console.log(this.$refs.childList.$data.name); // 调用子组件中的方法 this.$refs.childList.test1(); } } }
list.vue
组件中的数据:
export default { data() { return { name: 'list', version: '1.0.0' } }, methods: { test1() { console.log('test1'); }, test2() { console.log('test2'); } } }
子组件向父组件传值
注意:子组件同样也可以调用父组件中的方法,通过props传值即可
通过此种方法,子组件也可以传值给父组件
父组件中
<template lang="html"> <div class="home"> <list :func="test3"></list> </div> </template> <script> import List from '../components/list' export default { components: { List }, methods: { test3(value) { // 参数value就是子组件传递给父组件的值 console.log('test3', value); } } } </script> <style lang="css"> </style>
子组件中
<template lang="html"> <div class="list"> <ul> <li>1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ul> <button @click="userParentFunc()">调用父组件中的方法</button> </div> </template> <script> export default { props: ['func'], methods: { userParentFunc() { this.func('我是子组件中的数据'); } } } </script> <style lang="css" scoped> </style>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了