Vue中ref的用法及演示
ref 定義:被用來給元素或子組件注冊引用信息。引用信息會被注冊在父組件上的$refs對象上。
- 如果是在普通的
dom
元素上使用,引用指向的就是dom
元素; - 如果用在子組件上,引用指向的就是組件實例。
舉例:
組件1:
<template> <div> 我是{ {name}} </div> </template> <script> export default { name:'Cpn1', data() { return { name:'組件1' } }, } </script>
組件2:
<template> <div>我是{ {name}}</div> </template> <script> export default { name:'Cpn2', data() { return { name:'組件2' } }, } </script>
App.vue
<template> <div id="app"> <cpn-1 ref="c1"></cpn-1> <cpn-2 ref="c2"></cpn-2> <button @click="showDom">按鈕</button> <h2 ref="title">我是標題</h2> <input type="text" ref="input" value="123"> </div> </template> <script> import Cpn1 from "./components/Cpn1.vue"; import Cpn2 from "./components/Cpn2.vue"; export default { components: { Cpn1, Cpn2 }, name: "App", methods: { showDom() { console.log(this.$refs.c1); console.log(this.$refs.c2.$data.name); console.log(this.$refs.title) console.log(this.$refs.input.value) // 獲取一個真實的dom對象并修改值 var title=this.$refs.title; title.innerText="helloWord" }, }, }; </script>
執(zhí)行上面的程序,點擊頁面上的《按鈕》,效果如下:
同時看控制臺:
可以看到當ref對象用在普通元素上時獲取到的是普通DOM元素,當ref用在子組件上時,引用指向組件實例。
根據(jù)實際需要,可以通過ref給元素或者子組件注冊引用信息,在需要用到的時候我們可以通過$refs獲取真實的DOM元素或者組件實例進行我們想要的操作。
到此這篇關于Vue中ref的用法及演示的文章就介紹到這了,更多相關Vue中ref的用法內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
vue 監(jiān)聽鍵盤回車事件詳解 @keyup.enter || @keyup.enter.native
今天小編就為大家分享一篇vue 監(jiān)聽鍵盤回車事件詳解 @keyup.enter || @keyup.enter.native,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-08-08