当我在 Vue for NativeScript 中使用 v-for 时,函数 focus() 停止工作

The function focus() stops working when I use v-for in Vue for NativeScript

我有很多文本字段,我需要先按下按钮来设置焦点。

没有 v-forcode in the playground 有一小段工作正常。

但是当我开始使用 v-for 时程序停止运行。有一小段 code in the playgroundv-for,如果我按下按钮,程序就会崩溃。

我不明白我在哪里犯了错误,也不知道我必须做什么才能使这段代码正常工作。

<template>
    <Page>
        <ActionBar title="Home" />
        <ScrollView>
            <StackLayout class="home-panel">
                <Label textWrap="true" text="Test focus()!"
                    class="h2 description-label" />

                <TextField v-for="(item, index) in array"
                    v-model="array[index]" :key="'key'+index"
                    :ref="'ref' + index" />

                <Button text="Button" @tap="onButtonTap" />
            </StackLayout>
        </ScrollView>
    </Page>
</template>

<script>
    export default {
        methods: {
            onButtonTap() {
                console.log("Button was pressed");
                this.$refs["ref0"].nativeView.focus();
            }
        },

        data() {
            return {
                array: ["Hello", "World!"]
            };
        }
    };
</script>

在使用 v-for 时,您可以简单地分配一个静态 ref 并通过索引访问其中的项目。

<TextField v-for="(item, index) in array"
     v-model="array[index]" :key="'key'+index" ref="myTxt" />

  .....

  onButtonTap() {
     console.log("Button was pressed");
     this.$refs.myTxt[0].nativeView.focus();
  }