当我用:ref="testThis" v绑定一个元素引用时,它似乎停止了工作。比较有效的this version:
<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>使用不起作用的this one:
<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),所以我需要绑定。为什么它不工作/抛出错误?
发布于 2018-01-22 06:42:24
在vue文档I find中,引用是非反应性的:"$refs也是非反应性的,因此您不应该尝试在用于数据绑定的模板中使用它。“
我想这和我的情况相符。
我的实际问题“如何引用v-for列表中的项”并不容易解决,因为不使用绑定的引用,因为vue将所有类似的项引用放在一个数组中,而是使用it loses (v-for index) order。
我有另一个相当复杂的单文件组件,使用这段代码可以很好地工作:
:ref="'file' + parentIndex.toString()"在输入元素中。与我的问题示例唯一不同的是,parentIndex是一个组件属性。
总而言之,目前它有点让人困惑,因为从this来看,绑定引用在较早的vue版本中是允许的。
编辑:使用testThis() does work触发方法。
发布于 2018-01-22 07:34:04
如果你想使用一个方法,你需要在绑定中使用调用括号,让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>
https://stackoverflow.com/questions/48372264
复制相似问题