vue中的ref其實功能很強大,下面介紹一下如何使用。
基本用法,本頁面獲取dom元素
<template> <div id="app"> <div ref="testDom">11111</div> <button @click="getTest">獲取test節點</button> </div> </template> <script> export default { methods: { getTest() { console.log(this.$refs.testDom) } } }; </script>

image.png
其實ref除了可以獲取本頁面的dom元素,還可以拿到子組件中的data和去調用子組件中的方法
獲取子組件中的data
子組件
<template> <div> {{ msg }} </div> </template> <script> export default { data() { return { msg: "hello world" } } } </script>
父組件
<template> <div id="app"> <HelloWorld ref="hello"/> <button @click="getHello">獲取helloworld組件中的值</button> </div> </template> <script> import HelloWorld from "./components/HelloWorld.vue"; export default { components: { HelloWorld }, data() { return {} }, methods: { getHello() { console.log(this.$refs.hello.msg) } } }; </script>

image.png
調用子組件中的方法
子組件
<template> <div> </div> </template> <script> export default { methods: { open() { console.log("調用到了") } } } </script>
父組件
<template> <div id="app"> <HelloWorld ref="hello"/> <button @click="getHello">獲取helloworld組件中的值</button> </div> </template> <script> import HelloWorld from "./components/HelloWorld.vue"; export default { components: { HelloWorld }, data() { return {} }, methods: { getHello() { this.$refs.hello.open(); } } }; </script>

image.png
子組件調用父組件方法
子組件
<template> <div> </div> </template> <script> export default { methods: { open() { console.log("調用了"); // 調用父組件方法 this.$emit("refreshData"); } } } </script>
父組件
<template> <div id="app"> <HelloWorld ref="hello" @refreshData="getData"/> <button @click="getHello">獲取helloworld組件中的值</button> </div> </template> <script> import HelloWorld from "./components/HelloWorld.vue"; export default { components: { HelloWorld }, data() { return {} }, methods: { getHello() { this.$refs.hello.open() }, getData() { console.log('111111') } } }; </script>

image.png
未完待續
作者:回不去的那些時光
鏈接:https://www.jianshu.com/p/623c8b009a85
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯系作者獲得授權並注明出處。