在带参数的函数内部动态使用 Vue $refs
Using Vue $refs dynamically inside of function with parameter
我正在尝试使用 $refs
功能通过 Vue 访问 DOM 元素,但我无法使其正常工作。
我的元素如下所示。 plateId是动态生成的,所以不会一直是同一个数字:
<textarea :ref="plateId + '-notes'">
我的 Vue 函数如下所示:
/* This does not work */
addNotes: function(plateId) {
console.log(this.$refs.plateId + '-notes');
}
每当我 运行 此代码和功能被激活时,它只会在我的控制台中读取 undefined
。我也试过这个,它也不起作用并且读取未定义:
/* This does not work */
addNotes: function(plateId) {
var plateIdNotes = plateId + '-notes';
console.log(this.$refs.plateIdNotes);
}
用const
替换var
(我正在使用ES6并转译代码)也不起作用:
/* This does not work */
addNotes: function(plateId) {
const plateIdNotes = plateId + '-notes';
console.log(this.$refs.plateIdNotes);
}
我知道 ref
正确绑定到元素,因为当我在下面执行此操作时,我可以在控制台中看到我的所有其他引用,以及 plateId-notes ref:
/* This works */
addNotes: function(plateId) {
console.log(this.$refs);
}
如何使用函数中的参数访问 plateId
ref?
您可以使用 []
表示法:
methods: {
foo (id) {
alert(this.$refs[id + '-test'].innerText)
}
}
一个完整的工作示例:https://jsfiddle.net/drufjsv3/2/
此外,您可以通过访问
来访问在视图中呈现的所有 $refs
vm.$children.forEach( child => {
var tag = child.$vnode.data.ref;
console.log(vm.$refs[tag]);
vm.$refs[tag].loadData();
});
// loadData() is a method to implement when mounted or when you want to reload data
//////////////////////////////////
<script>
export default {
data() {
return {
notifications: []
}
},
mounted() {
this.loadData();
},
methods: {
loadData: function() {
axios.get('/request-json/notifications').then(res => {
this.notifications = res.data;
});
},
.....
我正在尝试使用 $refs
功能通过 Vue 访问 DOM 元素,但我无法使其正常工作。
我的元素如下所示。 plateId是动态生成的,所以不会一直是同一个数字:
<textarea :ref="plateId + '-notes'">
我的 Vue 函数如下所示:
/* This does not work */
addNotes: function(plateId) {
console.log(this.$refs.plateId + '-notes');
}
每当我 运行 此代码和功能被激活时,它只会在我的控制台中读取 undefined
。我也试过这个,它也不起作用并且读取未定义:
/* This does not work */
addNotes: function(plateId) {
var plateIdNotes = plateId + '-notes';
console.log(this.$refs.plateIdNotes);
}
用const
替换var
(我正在使用ES6并转译代码)也不起作用:
/* This does not work */
addNotes: function(plateId) {
const plateIdNotes = plateId + '-notes';
console.log(this.$refs.plateIdNotes);
}
我知道 ref
正确绑定到元素,因为当我在下面执行此操作时,我可以在控制台中看到我的所有其他引用,以及 plateId-notes ref:
/* This works */
addNotes: function(plateId) {
console.log(this.$refs);
}
如何使用函数中的参数访问 plateId
ref?
您可以使用 []
表示法:
methods: {
foo (id) {
alert(this.$refs[id + '-test'].innerText)
}
}
一个完整的工作示例:https://jsfiddle.net/drufjsv3/2/
此外,您可以通过访问
来访问在视图中呈现的所有 $refsvm.$children.forEach( child => {
var tag = child.$vnode.data.ref;
console.log(vm.$refs[tag]);
vm.$refs[tag].loadData();
});
// loadData() is a method to implement when mounted or when you want to reload data
//////////////////////////////////
<script>
export default {
data() {
return {
notifications: []
}
},
mounted() {
this.loadData();
},
methods: {
loadData: function() {
axios.get('/request-json/notifications').then(res => {
this.notifications = res.data;
});
},
.....