Answers:
v-el:el:uniquename
已由取代ref="uniqueName"
。然后通过访问元素this.$refs.uniqueName
。
ref
属性可用于任何HTML元素或Vue组件。好东西。
答案不清楚:
使用this.$refs.someName
,但是要使用它,必须添加ref="someName"
parent。
请参阅下面的演示。
new Vue({
el: '#app',
mounted: function() {
var childSpanClassAttr = this.$refs.someName.getAttribute('class');
console.log('<span> was declared with "class" attr -->', childSpanClassAttr);
}
})
<script src="https://unpkg.com/vue@2.5.13/dist/vue.min.js"></script>
<div id="app">
Parent.
<span ref="someName" class="abc jkl xyz">Child Span</span>
</div>
$refs
和 v-for
请注意,当与结合使用时v-for
,this.$refs.someName
将会是一个数组:
new Vue({
el: '#app',
data: {
ages: [11, 22, 33]
},
mounted: function() {
console.log("<span> one's text....:", this.$refs.mySpan[0].innerText);
console.log("<span> two's text....:", this.$refs.mySpan[1].innerText);
console.log("<span> three's text..:", this.$refs.mySpan[2].innerText);
}
})
span { display: inline-block; border: 1px solid red; }
<script src="https://unpkg.com/vue@2.5.13/dist/vue.min.js"></script>
<div id="app">
Parent.
<div v-for="age in ages">
<span ref="mySpan">Age is {{ age }}</span>
</div>
</div>
有关官方信息:
https://vuejs.org/v2/guide/migration.html#v-el-and-v-ref-replaced
一个简单的例子:
您必须在任何元素上添加ref
具有唯一值的属性
<input ref="foo" type="text" >
针对该要素使用 this.$refs.foo
this.$refs.foo.focus(); // it will focus the input having ref="foo"
this.$el
在安装之前是不确定的。如果您想初始化变量,请在mount()