vue中ref的作用
1.基本用法,本页面获取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>
其实ref除了可以获取本页面的dom元素,还可以拿到子组件中的data和去调用子组件中的方法:
2 获取子组件中的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>
3.调用子组件中的方法
子组件:
<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>
转载自:https://www.jianshu.com/p/623c8b009a85