9.关于ref的使用

1.在普通标签上可以使用ref来获取Dom

<div id="app">
			<p @click="handerClick" ref="pp" id="p">你好 web2208</p>
		</div>
		<script src="vue.js"></script>
		<script>
			const app = new Vue({
				el: "#app",
				data() {
					return {

					}
				},
				methods: {
					handerClick() {
						 console.log(document.getElementById('p'))
                       /* console.log(document.getElementById('p').innerHTML); */
					   console.log(this.$refs.pp.innerHTML);
					}
				},
				computed: {

				}
			})

2.ref可以实现组件间的通讯

<div id="app">
			<counter ref="one" @change="handelClick"></counter>
			<counter ref="two" @change="handelClick"></counter>
			<h2>{{total}}</h2>
			<!-- <button type="button" @click="change">+</button> -->
		</div>
		<script src="vue.js"></script>
		<script>
			Vue.component('counter', {
						template: `<div @click="handelclick">{{number}}</div>`,
						data() {
							return {
								number: 0
							}
						},
						methods: {
							handelclick() {
								this.number++;
								this.$emit('change');
							}
							}
						}) 
						const app = new Vue({
						el: "#app",
						data() {
							return {
								total:0
							}
						},
						methods: {
							handelClick() {
							this.total = this.$refs.one.number + this.$refs.two.number 
							}
						},
						computed: {

						}
					})

3.ref可以调用组件中的方法

<div id="app">
              <helloworld ref="hello"></helloworld>
              <button @click="getHello">获取helloworld组件中的值</button>
		</div>
		<script src="vue.js"></script>
		<script>
			Vue.component('helloworld',{
				template:'<div></div>',
				data(){
					return {
						number:0
					}
				},
				methods:{
					handelclick(){
						console.log('被调用了');
					}
				}
			})
			const app = new Vue({
				el: "#app",
				data: {
					
				},
				methods: {
                  getHello(){
					   this.$refs.hello.handelclick();
			                   console.log(this.$refs.hello.number);
					   console.log(this.$refs.hello);
				  }
				},
				computed:{
					
				}
			})

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值