ref
给元素或子组件添加ref属性,则该元素或者子组件实例对象会被添加到当前组件实例对象下的$refs属性中
$refs
该属性是一个对象,存储了通过ref绑定的元素对象或子组件实例对象
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="app">
<h1>{{title}}</h1>
<button @click="getBoxHeight">获取 box 的高度</button>
<button @click="getKKBComponent">获取自定义组件实例及内部方法</button>
<hr>
<div ref="box">
这是内容<br>这是内容<br>这是内容<br>这是内容<br>这是内容<br>
</div>
<hr>
<kkb-component ref="kkb" :t="title"></kkb-component>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
const kkbComponent = {
props: ['t'],
data() {
return {
isShow: true
}
},
template: `
<div v-if="isShow">
<h1>kkbComponent - {{t}}</h1>
</div>
`,
methods: {
hide() {
this.isShow = false;
}
}
}
let app = new Vue({
el: '#app',
data: {
title: '开课吧'
},
components: {
'kkb-component': kkbComponent
},
mounted() {
console.log(this.$refs.kkb);
},
methods: {
getBoxHeight() {
console.log( this.$refs.box.clientHeight );
},
getKKBComponent() {
this.$refs.kkb.hide();
}
}
});
</script>
</body>
</html>
网友评论