这个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 >
		<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 >
		<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>

分类:

技术点:

相关文章: