vue中的ref其實功能很強大,下面介紹一下如何使用。vue
<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和去調用子組件中的方法bash
子組件markdown
<template> <div> {{ msg }} </div> </template> <script> export default { data() { return { msg: "hello world" } } } </script> 複製代碼
父組件app
<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> 複製代碼
子組件dom
<template> <div> </div> </template> <script> export default { methods: { open() { console.log("調用到了") } } } </script> 複製代碼
父組件this
<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> 複製代碼
子組件spa
<template> <div> </div> </template> <script> export default { methods: { open() { console.log("調用了"); // 調用父組件方法 this.$emit("refreshData"); } } } </script> 複製代碼
父組件code
<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> 複製代碼
未完待續component