【问题标题】:Vue not updating input that depends on anotherVue不更新​​依赖于另一个的输入
【发布时间】:2017-05-29 12:31:48
【问题描述】:

我正在构建这样的东西,我选择的国家将自动指定电话国家代码。

country 和 countryCode 都存储在客户对象中,当我更改国家/地区的值时,触发器被正确调用,我可以在 Vue 开发工具中看到国家/地区代码发生​​变化,但是相关输入没有更新.这是我的代码:

    data: function () {
        return {
            customer: {},
            countries: this.$store.state.settings.countries,
        }
    },
    created: function() {
        var defaultCountry = _.find(this.countries, { default: true });

        this.customer.country = defaultCountry.name;
        this.customer.countryCode = defaultCountry.code;
    },
    methods: {
        updateCountryCode: function(country) {
            this.customer.countryCode = country.code;
        },
    }

这是相关的 HTML:

<vSelect 
label="name" 
v-model="customer.country" 
:options="countries" 
:onChange="updateCountryCode">
</vSelect>

<input type="text" disabled :value="customer.countryCode">

我做错了什么?为什么我在开发工具上看到数据正在更新,但它没有反应,而且我的国家/地区代码输入保持不变?

【问题讨论】:

  • 你应该像这样定义你的客户对象customer: {country: null, countryCode: null,},
  • 什么?那行得通!我假设因为我在 created() 上设置了默认值,所以我不需要在空对象中分配这些值。知道为什么需要这样做吗?另外,请将其添加为单独的答案,以便我可以将其标记为已解决:)

标签: javascript vue.js vuejs2


【解决方案1】:

你应该像这样定义你的客户对象:

{
    country: null, // or some other default value
    countryCode: null,
}, 

您可以在文档here中找到更多详细信息

【讨论】:

    【解决方案2】:

    这就是你应该这样做或@Nora 将对象属性初始化为null 的方法

     updateCountryCode: function(country) {
       this.$set(this.customer, 'countryCode', country.code) 
    }, 
    

    而原因是因为change detection caveats in vue reactivity

    【讨论】:

    • 谢谢你——我不确定这是否在臭名昭著的 Vue 警告中,但现在我明白了。
    • @Anonymous 乐于助人:)
    猜你喜欢
    • 2018-11-07
    • 1970-01-01
    • 2016-06-12
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-09
    相关资源
    最近更新 更多