this.$refs[("p" + index)].focus 不是函数
this.$refs[("p" + index)].focus is not a function
我想在点击时将 div
变成输入框,以便可以编辑 post(在循环内呈现)。
这是 post 上的按钮:
<a @click="setFocusEdit(index)" v-if="isAuthor(post)" href="#" >Edit Me</a>
以及div
关注的:
<div :ref="'p' + index" class="post-description">
{{post.description}}
</div>
方法:
setFocusEdit(index) {
console.log('focusing on', index);
this.$refs['p' + index].focus();
},
但是我得到这个错误:
Uncaught TypeError: this.$refs[("p" + index)].focus is not a function
我该如何解决这个问题?
由于您使用的是 v-for
,因此您应该使用具有静态名称的 ref
属性,例如 posts
,它为您提供了一个引用元素数组
new Vue({
el: '#app',
data: function() {
return {
posts: [{
title: "post 1",
content: "content 1"
},
{
title: "post 2",
content: "content 2"
}
],
}
},
methods: {
setFocusEdit(index) {
this.$refs.posts[index].focus();
}
},
mounted() {
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<div class='col-md-4 mt-3' v-for="(post, index) in posts" :key="index">
<textarea readonly ref="posts" class="post-description">
{{post.content}}
</textarea>
<a @click.prevent="setFocusEdit(index)" href="#">Edit Me</a>
</div>
</div>
我想在点击时将 div
变成输入框,以便可以编辑 post(在循环内呈现)。
这是 post 上的按钮:
<a @click="setFocusEdit(index)" v-if="isAuthor(post)" href="#" >Edit Me</a>
以及div
关注的:
<div :ref="'p' + index" class="post-description">
{{post.description}}
</div>
方法:
setFocusEdit(index) {
console.log('focusing on', index);
this.$refs['p' + index].focus();
},
但是我得到这个错误:
Uncaught TypeError: this.$refs[("p" + index)].focus is not a function
我该如何解决这个问题?
由于您使用的是 v-for
,因此您应该使用具有静态名称的 ref
属性,例如 posts
,它为您提供了一个引用元素数组
new Vue({
el: '#app',
data: function() {
return {
posts: [{
title: "post 1",
content: "content 1"
},
{
title: "post 2",
content: "content 2"
}
],
}
},
methods: {
setFocusEdit(index) {
this.$refs.posts[index].focus();
}
},
mounted() {
}
})
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
<div class='col-md-4 mt-3' v-for="(post, index) in posts" :key="index">
<textarea readonly ref="posts" class="post-description">
{{post.content}}
</textarea>
<a @click.prevent="setFocusEdit(index)" href="#">Edit Me</a>
</div>
</div>