$refs Vue 中的属性 用于引用 DOM 元素 。
一个常见的用例 $refs 元素 。 当某个事件发生时,专注于 DOM 这 autofocus 属性 适用于页面加载。 但是如果您想将注意力重新集中在 username 登录失败时输入?
如果你给 username 输入一个 ref 属性,然后您可以访问 username 输入使用 this.$refs.username 如下所示。 然后你可以调用 内置 Element#focus() 功能 赋予焦点的 username 输入。
const app = new Vue({
data: () => ({ username: , password: , failed: false }),
methods: {
login: async function() {
// Simulate that login always fails, just for this example
this.failed = true;
// Give focus back to `username` input. If you change the
// ref attribute in the template to usernameRef, you
// would do `this.$refs.usernameRef` here.
this.$refs.username.focus();
}
},
template: `
<div>
<input type=text v-model=username ref=username>
<input type=password v-model=password>
<button v-on:click=login()>Login</button>
<div v-if=failed>
Login Failed!
</div>
</div>
`
});
和 v-for 一起使用
当你使用 ref 与 _ v-for 指令 ,Vue 为您提供了一个原生 JavaScript 元素数组,而不仅仅是单个元素。
例如,假设您有一个列表 <input> 标签,并且您希望用户能够使用向上和向下箭头键在输入之间导航。
您可以访问个人 <input> 元素使用 $refs 并调用 focus() 每当用户向上或向下按下时:
const app = new Vue({
data: () => ({ cells: [foo, bar, baz].map(val => ({ val })) }),
mounted: function() {
let cur = 0;
this.$refs.inputs[0].focus();
document.addEventListener(keyup, ev => {
console.log(Got event, ev)
cur = this.$refs.inputs.findIndex(el => document.activeElement === el);
if (cur === -1) {
cur = 0;
}
const numEls = this.cells.length;
if (ev.keyCode === 38) { // Up arrow
cur = (numEls + cur - 1) % numEls;
this.$refs.inputs[cur].focus();
} else if (ev.keyCode === 40) { // Down arrow
cur = (cur + 1) % numEls;
this.$refs.inputs[cur].focus();
}
});
},
template: `
<div>
<div v-for=cell in cells>
<input v-model=cell.val ref=inputs>
</div>
</div>
`
});
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END








请登录后查看评论内容