這個ref只能進行子傳父,也比較簡單,調用也簡單,在想獲取的元素標簽里加上“ref”和名字即可(ref="name"),如<div ref="box">123456</div>/<son ref="son"></son>
,用this.$refs.box.innerHTML/this.$refs.son.sonMsg
得到即可
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app">
<div ref="box">123456</div>
<son ref="son"></son>
<button @click="getSonMsg">拿到子組件</button>
<button @click="getfatMsg">子傳父</button>
<button @click='getdom'>拿到dom節點</button>
<h3>子組件傳父組件信息:{{getson}} </h3>
</div>
<template id="son">
<div>
<h2>子組件信息:{{sonMsg}}</h2>
</div>
</template>
<script src="vue.js"></script>
<script>
// 子組件
Vue.component("son",{
template:"#son",
data(){
return{
sonMsg:"我是子組件信息"
}
}
})
// 父組件
new Vue({
el:"#app",
data:{
getson:'父組件'
// getson:''
},
methods:{
getSonMsg(){
console.log (this.$refs.son.sonMsg) //得到子組件信息
},
getfatMsg(){
this.getson = this.$refs.son.sonMsg //子傳父 (父組件信息)
console.log(this.getson)
},
getdom(){
console.log(this.$refs.box.innerHTML)
}
}
})
</script>
</body>
</html>