【问题标题】:The function focus() stops working when I use v-for in Vue for NativeScript当我在 Vue for NativeScript 中使用 v-for 时,函数 focus() 停止工作
【发布时间】:2019-12-06 01:33:00
【问题描述】:

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

code in the playground 的最小部分没有 v-for 可以正常工作。

但是当我开始使用 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>

【问题讨论】:

  • 给这个this.$refs["ref0"][0].nativeView.focus();添加0索引怎么样?

标签: javascript vue.js nativescript nativescript-vue


【解决方案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();
  }

【讨论】:

    猜你喜欢
    • 2019-11-08
    • 2016-11-12
    • 1970-01-01
    • 1970-01-01
    • 2021-09-10
    • 1970-01-01
    • 2019-08-12
    • 1970-01-01
    • 2017-01-03
    相关资源
    最近更新 更多