- 被用来给元素或子组件注册引用信息(原生js的替代者)
-
ref用在html标签上获取的是真实的DOM元素,应用在组件标签上是组件实例对象(vc)
-
使用方法:
打标识:<h1 v-text="msg" ref="title"></h1> 获取:this.$ref.xxx
父组件:
<template>
<div>
<!-- 原生的js给元素打标识用id,而vue用ref -->
<h1 v-text="msg" ref="title"></h1>
<button @click="showDom">点我输入上方的DOM元素</button>
<hello-world-vue></hello-world-vue>
</div>
</template>
<script>
import HelloWorldVue from './components/HelloWorld.vue'
export default {
name:'App',
components:{HelloWorldVue},
data(){
return{
msg:'这是一个h1标签'
}
},
methods:{
showDom(){
// this是vueComponet 组件的实例对象
console.log(this.$refs.title)
}
}
}
</script>
<style>
</style>
子组件:
<template>
<div>组件的名字{{name}}</div>
</template>
<script>
export default {
name:'HellWorld',
data(){
return{
name:'这是一个组件'
}
}
}
</script>
<style>
</style>