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

时间:2019-12-06 01:33:00

标签: javascript vue.js nativescript nativescript-vue

我有很多textField,我首先需要通过按按钮设置焦点。

至少有一个code in the playground,没有 v-for 可以正常工作。

但是当我开始使用v-时,程序停止工作。最小的code in the playground中带有 v-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>

1 个答案:

答案 0 :(得分:1)

使用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();
  }