(一)、动态绑定id
//动态绑定id
<button @click="insertAtCursor(item,index)" type="button" :id="'btn'+index">插入字</button>
//<button @click="insertAtCursor(item,index)" type="button" :id="`btn${index}`">插入字</button>
methods:{
insertAtCursor(){
console.log(document.querySelector('#btn'+index));
console.log(document.getElementById('btn'+index));//两种方法均可
}
}
打印结果:
(二)、ref在v-for循环中不能动他绑定,但可以根据根据元素的ref[index]动态的找到元素。因为v-for循环中,ref动态绑定需要的唯一标志还没有加载完成(我是这么理解的),可详见vue官方文档https://cn.vuejs.org/v2/api/#ref
在项目中我根据需求解决这个问题
<!--循环-->
<div style="display:flex;flex-direction:column;">
<div class="el-textarea" v-for="(item,index) in shoppeList" :key="index">
//添加一个class,以便于区分打印的是否正确
<textarea type="textarea" rows="10" autocomplete="off" :class="`class${index}`" ref="ttl"></textarea>
<button @click="insertAtCursor(item,index)" type="button">插入字段</button>
</div>
</div>
data(){
return{
shoppeList: [{id: 3,value: "name",},{id: 4,value: "sex"}],
}
},
menthods:{
insertAtCursor(item, index) {
console.log(this.$refs.ttl[index])
}
}
打印结果:
(三)注意:针对ref这种,我再使用elementui的时候,发现ref是可以绑定动态值的 ,这是基于在elemenui框架中表格加载完成以后,在渲染表格内部的元素,此时利用插槽可以拿到表格的index,这样ref在使用的时候动态的ingdx就是有的
举例:
<!-- elementui 框架表格中使用动态的ref -->
<el-table :data="shoppeList">
<el-table-column prop="">
<template slot-scope="scope">
<div>
//绑定一个动态的id以至于区分
<textarea :rows="8" placeholder="请输入内容 " :id="'textareaId'+scope.$index"
:style="{color:scope.row.color}" :ref="'ttl'+scope.$index">
</textarea>
<el-button @click="insertField(scope.$index,scope.row)">点击</el-button>
</div>
</template>
</el-table-column>
</el-table>
data(){
return{
shoppeList: [ { id: 3, value: "name"}, { id: 4, value: "sex"}],
}
},
methods:{
insertField(index,item){
console.log(index,item);
console.log(this.$refs['ttl' + index]); // 注意:获取到的是一个数组
}
}
打印: 获取到的数据。具体调用哪一个子元素的可以this.$refs['ttl' + index][x](x是数组中对应的下标)
(四)、动态绑定v-model
在v-for循环中动态绑定v-moldel
1、绑定item的key值,v-model是双向绑定,这样的话在更改texarea的时候,item的value值也随之更改了。可优化成2
<div v-for="(item,index) in shoppeList" :key="index">
<span>{{item}}</span>
<textarea :rows="8" placeholder="请输入内容 " :id="'textareaId'+index" v-model="item.value">
</textarea>
</div>
2.优化
绑定一个自定义的:在文本中输入内容的时候他会给item添加一个content值,这样在以后需要赋值的时候既可以用了。
<div v-for="(item,index) in shoppeList" :key="index">
<span>{{item}}</span>
<textarea :rows="8" placeholder="请输入内容 " :id="'textareaId'+index" v-model="item.content">
</textarea>
</div>
效果: