Vue中$refs 使用详解

js中想要获取dom节点一般用document.querySelecto('.input'),然后获取input的值。 在vue中绑定ref就不需要在获取dom节点了,直接绑定在input上,然后 $refs 调用即可。$refs 的使用方法就是在元素或组件标签上添加ref属性指定一个引用信息,引用信息将会注册在父组件的$refs对象上,在js中使用$refs来指向DOM元素或组件实例;

1.基本用法

<template>
 
  <div class="hello">
 
    <p ref="testTxt">{{oldMsg}}</p>
 
    <button @click="changeMsg()">点击修改段落内容</button>
 
  </div>
 
</template>
 
<script>
 
export default {
 
    data(){
 
        return {
 
            oldMsg:'这是旧数据',
 
            newMsg:'hello,这是新数据!!!',
 
        }
 
    },
 
    methods:{
 
        changeMsg(){
 
            this.$refs.testTxt.innerHTML=this.newMsg;
 
        },
    
    }
 
}
 
</script>
2.获取子组件中的数据

父组件:

<template>
    <div class="parent">
    	<!-- 子组件标签上添加ref属性: ref="childItemId -->
        <Children ref="childItemId"></Children >
        <p style="color:blue;">{{msgFromChild}}</p>
        <button @click="getChildMsg()">使用$refs获取子组件的数据</button>
    </div>
</template>
 
<script>
import Children from './Children '
export default {
    components:{Children },
    data(){
        return {
            msgFromChild:'',
        }
    },
    methods:{
        getChildMsg(){
        	//父组件用$refs来获取子组件的数据
            this.msgFromChild=this.$refs.childItemId.childMsg;
            console.log(this.msgFromChild);//这是子组件的参数
            //父组件用$refs来调用子组件的方法
            this.$refs.childItemId.open();// 我是子组件
        },
    }
}
</script>
 

子组件:

<template>
    <div class="children"></div>
</template>
 
<script>
export default {
    data(){
        return {
            childMsg:'这是子组件的参数'
        }
    },
    methods:{
        open(){
      		console.log('我是子组件');
    	}
    }
}
</script>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值