# 1.$refs
# App
// App.vue | |
<template> | |
<div> | |
<!-- 绑定到一个元素上 --> | |
<h2 ref="title">Neko</h2> | |
<!-- 绑定到一个组件实例上 --> | |
<home ref="Home"></home> | |
<button @click="btnClick">获取元素</button> | |
</div> | |
</template> | |
<script> | |
import Home from './Home.vue'; | |
export default { | |
components: { | |
Home | |
}, | |
methods: { | |
btnClick() { | |
console.log("App:",this.$refs.title); // 获取绑定的的的元素 | |
console.log(this.$refs.Home.message); // 获取 Home 组件里面的 message | |
this.$refs.Home.sayHello(); // 调用 Home 组件里面的 sayHello 方法 | |
} | |
} | |
} | |
</script> | |
<style scoped></style> |
# Home
<template> | |
<div> | |
<h2>Home</h2> | |
</div> | |
</template> | |
<script> | |
export default { | |
data() { | |
return { | |
message: "Home:我是Home中的message" | |
} | |
}, | |
methods: { | |
sayHello() { | |
console.log("Home:Hello Home"); | |
}, | |
} | |
} | |
</script> | |
<style scoped></style> |
参考结果:
![ref_refs](ref_refs.gif)
# 2.$parent
// Home | |
<template> | |
<div> | |
<h2>Home</h2> | |
<button @click="getParent">获取父组件</button> | |
</div> | |
</template> | |
<script> | |
export default { | |
data() { | |
return { | |
message: "Home:我是Home中的message", | |
}; | |
}, | |
methods: { | |
sayHello() { | |
console.log("Home:Hello Home"); | |
}, | |
getParent() { | |
console.log(this.$parent); | |
}, | |
}, | |
}; | |
</script> | |
<style scoped></style> |
参考结果:
![ref_parent](ref_parent.gif)
# 3.$root
// Home | |
<template> | |
<div> | |
<h2>Home</h2> | |
<button @click="getRoot">获取根组件</button> | |
</div> | |
</template> | |
<script> | |
export default { | |
data() { | |
return { | |
message: "Home:我是Home中的message", | |
}; | |
}, | |
methods: { | |
sayHello() { | |
console.log("Home:Hello Home"); | |
}, | |
getRoot() { | |
console.log(this.$root); | |
}, | |
}, | |
}; | |
</script> | |
<style scoped></style> |
参考结果: 因为他的跟根组件也是 App,所以结果与 $parent 是一样的
![ref_root](ref_root.gif)
# 4.$el
# App
// App.vue | |
<template> | |
<div> | |
<!-- 绑定到一个元素上 --> | |
<h2 ref="title">Neko</h2> | |
<!-- 绑定到一个组件实例上 --> | |
<home ref="Home"></home> | |
<button @click="btnClick">获取子元素</button> | |
</div> | |
</template> | |
<script> | |
import Home from "./Home.vue"; | |
export default { | |
components: { | |
Home, | |
}, | |
methods: { | |
btnClick() { | |
console.log(this.$el); | |
}, | |
}, | |
}; | |
</script> | |
<style scoped>/style> |
# Home
// Home | |
<template> | |
<div> | |
<h2>Home</h2> | |
</div> | |
</template> | |
<script> | |
export default { | |
data() { | |
return { | |
message: "Home:我是Home中的message", | |
}; | |
}, | |
}; | |
</script> | |
<style scoped></style> |
参考结果:
![ref_el](ref_el.gif)