【Vue CLI脚手架开发】——2.ref属性
文章目录
- 前言
- 一、ref属性
- 二、使用步骤
- 1.实现代码
- 2.结果展示
前言
Vue 的 ref 属性是框架中用于直接访问 DOM 元素或子组件实例的核心特性,在模板中标记元素或子组件,通过 this.$refs 获取其引用,支持直接操作 DOM 或调用子组件方法。
一、ref属性
- 被用来给元素或子组件注册引用信息(id 的替代者)
- 应用在 html 标签上获取的是真实 DOM 元素,应用在组件标签上是组件实例对(vc)
- 使用方式:
- 打标识:
<h1 ref="xxx">.....</h1>
或<School ref="xxx"></School>
- 获取:
this.$refs.xxx
- 打标识:
二、使用步骤
1.实现代码
代码如下(示例):
school.vue
<template>
<div class="school">
<h2>学校名称:{{ name }}</h2>
<h2>学校地址:{{ address }}</h2>
</div>
</template>
<script>
export default {
name:'school',
data(){
return{
name:"vue学院",
address:"上海·黄浦"
}
}
}
</script>
<style scoped>
.school{
background-color: aliceblue;
}
</style>
App.vue
<template>
<div id="app">
<h1 v-text="msg" ref="title"></h1>
<button ref="btn" @click="showDom">点击我输出上面的DOM元素</button>
<school ref="sch"></school>
</div>
</template>
<script>
import school from './components/school.vue';
export default {
name: 'App',
components: {
school
},
data() {
return {
msg:"欢迎学习Vue"
}
},
methods: {
showDom(){
// 获取h1真实的DOM元素
console.log(this.$refs.title);
// 获取button真实的DOM元素
console.log(this.$refs.btn);
// 获取school组件的实例对象(VueComponnet的实例对象vc)
console.log(this.$refs.sch);
}
},
}
</script>