ref属性 1. 被用来给元素或子组件注册引用信息(id的替代者) 2. 应用在html标签上获取的是真实DOM元素,应用在组件标签上是组件实例对象(vc) 3. 使用方式: 1. 打标识:```<h1 ref="xxx">.....</h1>``` 或 ```<School ref="xxx"></School>``` 2. 获取:```this.$refs.xxx```
代码结构:
School.vue
<template> <div class="school"> <h2>学校名称:{{name}}</h2> <h2>学校地址:{{address}}</h2> </div> </template> <script> export default { name:'School', data() { return { name:'School', address:'北京·昌平' } }, } </script> <style> .school{ background-color: gray; } </style>
App.vue:
<template> <div> <h1 v-text="msg" ref="title"></h1> <button ref="btn" @click="showDOM">点我输出上方的DOM元素</button> <School ref="sch"/> </div> </template> <script> //引入School组件 import School from './components/School' export default { name:'App', components:{School}, data() { return { msg:'欢迎学习Vue!' } }, methods: { showDOM(){ console.log(this.$refs.title) //真实DOM元素 console.log(this.$refs.btn) //真实DOM元素 console.log(this.$refs.sch) //School组件的实例对象(vc) } }, } </script>
输出:
main.js
//引入Vue import Vue from 'vue' //引入App import App from './App.vue' //关闭Vue的生产提示 Vue.config.productionTip = false //创建vm new Vue({ el:'#app', render: h => h(App) })
标签:School,Vue,DOM,App,vue,ref,refs From: https://www.cnblogs.com/anjingdian/p/17006995.html