ref属性
ref属性被用来给元素或子组件注册引用信息(id的替代者),避免在vue中使用document.getElementById。
应用在html标签上时,获取的是真实dom元素;应用在组件标签上时,获取的是组件实例对象。
示例:
<template><div id="app"><!-- Html标签上使用ref属性 --><h1 v-text="msg" ref="title"></h1><button ref="btn" @click="showDom">点我输出dom</button><!-- 组件上使用ref --><School ref="sch" /></div></template><script>import School from './components/School'export default {name: 'App',components: {School},data() {return {msg: 'hello'}},methods: {showDom() {// 使用this.$refs获取到当前组件配置的refconsole.log(this.$refs); // 当前组件中所有的refconsole.log(this.$refs.title); // 获取到ref=title所在的dom元素console.log(this.$refs.sch); // 获取到ref=sch对应的组件}},};</script>
