vue的ref和$refs使用

1. 基本用法:在当前页面中获取dom元素

	<div id="app">
		<button @click="getRef" ref="button">获取该节点</button>
	</div>

<script>
	new Vue({
	el:'#app',
	methods:{
		getRef(){
			console.log(this.$refs.button)
		}
	}
});
</script>

2. 获取子组件中的data

	<div id="app1">
		<child @click.native="getChildData" ref="data"></child>
	</div>

<script>
	Vue.component('child',{
				data(){
					return{
						msg:'hello'
					}
				},
				template:'<button>获取子组件中的data</button>'
			})
			new Vue({
				el:'#app1',
				methods:{
					getChildData(){
						console.log(this.$refs.data.msg)
					}
				}
			});
</script>

3. 获取子组件中的方法

	<div id="app2">
		<button @click="getChildMethod">获取子组件中的方法</button>
		<child-a ref="meth"></child-a>
	</div>

<script>
	Vue.component('child-a',{
				methods:{
					method(){
						console.log('调用成功')
					}
				},
				template:'<div></div>'
			})
			new Vue({
				el:'#app2',
				methods:{
					getChildMethod(){
						this.$refs.meth.method()
					}
				}
			});
</script>

4. 子组件调用父组件的方法

例一:

<div id="root">
    <counter ref="one" @change="handleChange"></counter>
    <counter ref="two" @change="handleChange"></counter>
    <div>{{total}}</div>
</div>

<script>

    Vue.component('counter',{
        template: '<div @click="handleClick">{{ number }}</div>',
        data: function(){
            return {
                number: 0
            }
        },
        methods: {
            handleClick: function () {
                this.number ++
                this.$emit('change')
            }
        }
    })

    var vm =new Vue({
        el: "#root",
        data: {
            total: 0
        },
        methods: {
            handleChange: function () {
                this.total= this.$refs.one.number + this.$refs.two.number
                console.log(this.$refs.one.number)
                console.log(this.$refs.two.number)
            }
        }
    })

例二:

	<div id="app3">
		<child-b ref="hello" @refresh="getData"></child-b>
		<button @click="getFatherMethod">按钮</button>
	</div>

<script>
	Vue.component('child-b',{
				methods:{
					open(){
						console.log("111")
						this.$emit('refresh')
					}
				},
				template:'<div></div>'
			})
			new Vue({
				el:'#app3',
				methods:{
					getFatherMethod(){
						this.$refs.hello.open()
					},
					getData(){
						console.log('调用成功')
					}
				}
			});
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值