在vue.js中设置值会给出`undefined`值

时间:2017-02-07 07:05:37

标签: javascript vue.js

当vue组件通过websocket接收更新时,它为<select>设置了新值。

相关代码

            window.VueBus.$on("updated", (channel, key, value) => {
             let selfChannel = "model." + self.model + "." + self.pk;
             if(channel === selfChannel) {
                 if(self.key === key) {
                     console.log("Set " + key + " to " + value);
                     self.input.off("change");
                     console.log("off handler");
                     self.value = value; // when I set value here error happens
                     self.$nextTick(() => {
                         self.input.on("change", this.onInputChange);
                         console.log("on handler");
                         self.initInput(true);
                     });
                 }
             }
         });

我已经添加了监视功能

        watch: {
         value: function(old, newv) {
             console.log('old-new');
             console.log(old)
             console.log(newv)
         }
     },

当我打开两个浏览器窗口并在其中一个窗口中进行更改时,这就是它给我的。

old-new
19
      # it is just an empty string
old-new
undefined
19

但是我看到正确的值传递给组件

Set recommender_id to 19
off handler # it is required because onInputChange makes requests to server

控制台上的错误

TypeError: Cannot read property 'length' of undefined

这是因为模板中的这一行

<div v-bind:class="{'floating-label-form-group-with-value': value.length > 0}">

在另一个窗口(我做出改变的地方)一切都很好。

1 个答案:

答案 0 :(得分:0)

解决方案很简单:https://github.com/vuejs/vue/issues/4524

v-model on <select> sets the value to undefined if the <select> is lacking the matching <option>