2020-07-04 ref和$refs

ref

????給元素或子組件添加ref屬性,則該元素或者子組件實(shí)例對象會被添加到當(dāng)前組件實(shí)例對象下的$refs屬性中

$refs

????該屬性是一個(gè)對象,存儲了通過ref綁定的元素對象或子組件實(shí)例對象

<!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">獲取自定義組件實(shí)例及內(nèi)部方法</button>

? ? ? ? <hr>

? ? ? ? <div ref="box">

? ? ? ? ? ? 這是內(nèi)容<br>這是內(nèi)容<br>這是內(nèi)容<br>這是內(nèi)容<br>這是內(nèi)容<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>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容