Vue中$refs 使用详解

本文介绍了Vue中$refs的基本用法及如何通过$refs获取DOM元素或子组件实例,包括直接修改DOM内容和调用子组件的方法。

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>
<think>我们被要求回答关于Vue2中this.$refs的灵活写法。引用内容提到了一些基本用法和注意事项: - 引用[1]说明了$refs用于获取虚拟DOM或组件实例 - 引用[2]展示了通过$refs调用子组件方法并传递参数 - 引用[3]则是一个常见错误,即在组件未渲染时访问$refs导致undefined 用户需求:查找Vue2中this.$refs的灵活写法 根据以上信息,我们可以组织回答如下: 1. 先解释this.$refs的基本用法:用于访问模板中通过ref属性标记的DOM元素或子组件实例。 2. 灵活写法的几个方面: a) 如何动态设置ref(使用字符串拼接或函数形式) b) 在v-for循环中使用ref(得到数组) c) 调用子组件方法(如引用[2]所示) d) 注意$refs不是响应式的,避免在模板和计算属性中使用 e) 处理可能为undefined的情况(如引用[3]的错误) 同时,生成相关问题。 注意:引用内容中有一些拼写错误(如“eidtshopDataf”可能是“editShopData”),但我们要按照原文引用标识。 由于用户要求灵活写法,重点应放在动态ref和避免错误上。 </think>### Vue2中`this.$refs`的灵活写法详解Vue2中,`this.$refs`是访问DOM元素或子组件实例的重要API。以下是灵活应用场景及写法: #### 1. **基础组件引用** ```javascript // 父组件 <ChildComponent ref="childRef" /> methods: { callChildMethod() { const result = this.$refs.childRef.childMethod(); // 直接调用子组件方法 this.$refs.childRef.data = "new value"; // 直接修改子组件数据 } } ``` #### 2. **动态`ref`名称** 使用计算属性动态生成`ref`标识符: ```javascript <template> <div v-for="item in list" :key="item.id"> <Child :ref="`child_${item.id}`" /> </div> </template> methods: { getSpecificChild(id) { return this.$refs[`child_${id}`]; // 动态访问特定实例 } } ``` #### 3. **函数式`ref`(Vue 2.6+)** 更灵活的控制引用生命周期: ```javascript <ChildComponent :ref="el => { if(el) childInstances.push(el) }" /> data() { return { childInstances: [] } } ``` #### 4. **多层组件穿透** 通过链式调用访问深层组件: ```javascript // 访问孙子组件 const grandChild = this.$refs.parentRef.$refs.grandChildRef; // 调用嵌套方法 this.$refs.formRef.$refs.inputRef.focus(); ``` #### 5. **异步安全访问** 确保DOM渲染完成后再操作(解决undefined问题): ```javascript this.$nextTick(() => { if(this.$refs.myComponent) { this.$refs.myComponent.doSomething(); // 安全调用 } }); ``` #### 6. **组合式参数传递** 引用[2]的优化写法(避免直接修改props): ```javascript // 父组件 this.$refs.child.processData( JSON.parse(JSON.stringify(this.rawData)) // 深拷贝避免污染源数据 ); // 子组件 methods: { processData(safeCopy) { /* 操作安全副本 */ } } ``` #### ⚠️ 注意事项 1. **`ref`非响应式**:避免在模板/computed中使用(引用[1]) 2. **`v-if`的影响**:被`v-if`控制的元素需在渲染后访问(引用[3]错误解决方案) 3. **`v-for`返回数组**:循环中的`ref`会收集为数组 4. **组件销毁后**:及时清除`ref`引用避免内存泄漏 > 引用示例:通过`$options`访问自定义属性时,`$refs`仍是访问组件/DOM的首选方案[^1] --- ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值