[英]binding a ref does not work in vue.js?
当我使用:ref="testThis"
v-bind 元素引用时,它似乎停止工作。 比较这个有效的版本:
<template>
<div>
<q-btn round big color='red' @click="IconClick">
YES
</q-btn>
<div>
<input
ref="file0"
multiple
type="file"
accept=".gif,.jpg,.jpeg,.png,.bmp,.JPG"
@change="testMe"
style='opacity:0'
>
</div>
</div>
</template>
<script>
import { QBtn } from 'quasar-framework'
export default {
name: 'hello',
components: {
QBtn
},
data () {
return {
file10: 'file0'
}
},
methods: {
IconClick () {
this.$refs['file0'].click()
},
testMe () {
console.log('continue other stuff')
}
}
}
</script>
使用这个不起作用:
<template>
<div>
<q-btn round big color='red' @click="IconClick">
YES
</q-btn>
<div>
<input
:ref="testThis"
multiple
type="file"
accept=".gif,.jpg,.jpeg,.png,.bmp,.JPG"
@change="testMe"
style='opacity:0'
>
</div>
</div>
</template>
<script>
import { QBtn } from 'quasar-framework'
export default {
name: 'hello',
components: {
QBtn
},
data () {
return {
file10: 'file0'
}
},
methods: {
IconClick () {
this.$refs['file0'].click()
},
testThis () {
return 'file0'
},
testMe () {
console.log('continue other stuff')
}
}
}
</script>
第一个有效。 第二个抛出错误:
TypeError: Cannot read property 'click' of undefined
at VueComponent.IconClick
因为我想根据列表索引(此处未显示,但它解释了我需要绑定 ref)来改变 ref,所以我需要绑定。 为什么它不起作用/抛出错误?
在 vue 文档中,我发现ref 是非反应性的:“$refs 也是非反应性的,因此您不应尝试在模板中使用它来进行数据绑定。”
我认为这符合我的情况。
我的实际问题“如何引用 v-for 列表的项目”并不容易解决,因为 vue 将所有类似的 item-refs 放入数组中,但它失去了 (v-for index) order 。
我有另一个相当精细的单文件组件,使用这段代码可以正常工作:
:ref="'file' + parentIndex.toString()"
在输入元素中。 与我的问题示例的唯一区别是parentIndex
是一个组件属性。
总而言之,它目前有点令人困惑,因为从这里看起来绑定 ref 在早期的 vue 版本中是允许的。
编辑:用testThis()
触发方法确实有效。
如果你想使用一个方法,你需要在绑定中使用调用括号,让 Vue 知道你希望它绑定调用的结果,而不是函数本身。
:ref="testThis()"
我认为下面的代码片段可以按您的预期工作。 我使用computed
而不是方法。
new Vue({ el: '#app', data() { return { file10: 'file0' } }, computed: { testThis() { return 'file0'; } }, methods: { IconClick() { this.$refs['file0'].click() }, testMe() { console.log('continue other stuff') } } });
<script src="//cdnjs.cloudflare.com/ajax/libs/vue/2.4.2/vue.min.js"></script> <div id="app"> <q-btn round big color='red' @click="IconClick"> YES </q-btn> <div> <input :ref="testThis" multiple type="file" accept=".gif,.jpg,.jpeg,.png,.bmp,.JPG" @change="testMe" style='opacity:0'> </div> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.