Vue中this.$refs的使用及說明
更新時間:2025年08月26日 14:39:59 作者:咸魚妹妹
Vue中this.$refs用于訪問通過ref注冊的元素或組件,需在mounted后使用,可在JS操作DOM或調(diào)用子組件方法,注意避免模板中直接使用
Vue使用this.$refs
父組件
<template>
<div>
<!--
ref 寫在標簽上時:this.$refs.名字 獲取的是標簽對應的dom元素
ref寫在組件上時:這時候獲取到的是子組件(比如navChild)的引用
-->
<Child ref="navChild"/>
</div>
</template>
<script>
import Child from "@/components/child";
export default {
name: "App",
methods: {
navFn(){
// this.$refs.navChild 或者 this.$refs['navChild']
// 第一種使用情況(父組件調(diào)用子組件的方法)
this.$ref.navChild.initData();
// 第二種使用情況(父組件調(diào)用子組件的方法,并通過方法傳值)
this.$refs.navChild.initData('我是父組件的傳值')
// 第四種使用情況(父組件獲取子組件的數(shù)據(jù))
this.$ref.navChild.status
// 第四種使用情況(父組件獲取子組件的數(shù)據(jù),并改變數(shù)據(jù))
this.$ref.navChild.status = 1;
}
},
};
</script>
子組件
<template>
<div>
<div>{{message}}</div>
</div>
</template>
<script>
export default {
name: "Child",
data() {
return {
message:'這是子組件',
status:0
};
},
components: {},
created() {
console.log(this.$data.status); //1(通過this.$data獲取所有變量)
this.status = this.$data.status;
},
methods:{
initData(val){
// 方法二:獲取父組件的傳值
console.log(val); //我是父組件的傳值
this.message = val;
let name = 'Hello World';
}
}
};
</script>
<style scoped>
</style>
總結
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持腳本之家。

