【问题标题】:NativeScript-vue custom switch not workingNativeScript-vue 自定义开关不起作用
【发布时间】:2020-08-07 07:15:13
【问题描述】:

我正在尝试制作一个可重复使用的自定义 Switch 组件,但我的 v-model 无法正常工作。情况如下:

  • 我的组件正确地发出了点击事件
  • 我的组件正确更新了它的数据
  • 但是,尽管使用 v-model 连接到子级,但父级数据不会更新

这里有一些显示我的设置的 sn-ps:

// MY COMPONENT
<template>
  <Switch
    dock="right"
    backgroundColor="red"
    offBackgroundColor="yellow"
    v-model="model"
  />
</template>

<script>
export default {
  name: "SettingsSwitch",
  props: {
    value: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      model: this.value
    };
  },
  watch: {
    model: function(value) {
      this.$emit("tap", value);
    }
  }
};
</script>

在下面的示例中,我有 2 个开关: - 一个正常工作并且其数据得到更新的正常工作 - 链接到我的子组件且数据未更新的那个

// My parent view
<template>
  <ViewWrapper viewTitle="Change your settings" pageColor="tertiary">
    <StackLayout class="content-wrapper">
      <StackLayout class="category-wrapper">
        <DockLayout class="field-wrapper" stretchLastChild="true">
          <Switch v-model="myCheck" dock="right" @tap="test" /> 
          <StackLayout>
            <Label text="Mon label" class="field-label" />
            <Label text="Ma valeur actuelle" class="field-value" />
          </StackLayout>
        </DockLayout>
        <DockLayout class="field-wrapper" stretchLastChild="true">
          <SettingsSwitch v-model="myCheck2" @tap="test2" />
          <StackLayout>
            <Label text="Mon label" class="field-label" />
            <Label text="Ma valeur actuelle" class="field-value" />
          </StackLayout>
        </DockLayout>

      </StackLayout>
    </StackLayout>
  </ViewWrapper>
</template>

<script>
import { ViewWrapper } from "@/components";
import SettingsSwitch from "./SettingsSwitch";
export default {
  name: "Settings",
  components: { ViewWrapper, SettingsSwitch },

  data() {

    return {
      myCheck: false,
      myCheck2: false
    };
  },
  methods: {
    test() {
      console.log(this.myCheck);
    },
    test2(v) {
      console.log("emit", v); // <--- Value changes each time
      console.log("model", this.myCheck2); // <--- Value never changes
    }
  }
};
</script>

我尝试过使用不同的设置,例如删除 watch 并直接调用执行 $emit 的方法,但似乎无法解决问题

有什么想法吗?

【问题讨论】:

    标签: vue.js nativescript nativescript-vue


    【解决方案1】:

    所以我设法解决了我的问题。我的错误是我在我的组件中发出了tap 而不是input。我觉得自己很愚蠢,但我要放弃这个,而不是有人像我一样挣扎

    底线是:

    您可以在任何标签上使用 v-model,但是为了更新它的值,它需要接收带有一些数据的“输入”事件。这就是为什么我的子组件必须执行this.$emit("input", value);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-13
      • 1970-01-01
      • 2019-12-25
      • 2023-03-15
      • 1970-01-01
      • 2020-06-03
      • 2019-09-04
      • 2019-08-09
      相关资源
      最近更新 更多