V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
shintendo
V2EX  ›  Vue.js

Vue 的一个问题,虽然没什么用但是想搞清楚原因

  •  
  •   shintendo · 2018-09-15 11:43:08 +08:00 · 3436 次点击
    这是一个创建于 2021 天前的主题,其中的信息可能已经有所发展或是发生改变。

    问题:

    为什么 new Vue({data: {a: 123})不会报错,而 new Vue({data: new Date()})会报"data functions should return an object"呢?

    注意不是问 data 为什么要 function,而是{a: 123}和 new Date()都是 Object,为什么后者会报错,本质区别在什么地方?

    关于为什么要传这么奇怪的参数:

    是这样的,我在用 ElementUI 里面的$message.error()方法的时候,不小心传了个 Error 对象进去(应该传 message 字符串或者 options 对象),然后就报出了上述错误。出于好奇,我研究了一下 Element 的源码,发现这个参数最终是被传给了 new Vue({data: xxx}), 也就是说是 new Vue({data: new Error()})这句话报了上面的错。

    然后我又试了一下,new Vue({data: xxx})里面,xxx 用任何 js 内置对象(Date/Array/Boolean...)都报"data functions should return an object",而用自定义的对象就不会,又打开 vue 的源码,搜了一下这句话没搜到,到这里我就无能为力了。

    这问题好像没什么意义,毕竟正常人不会用内置对象去做组件 data,但是没弄清楚浑身难受。

    6 条回复    2018-09-15 15:13:58 +08:00
    noe132
        1
    noe132  
       2018-09-15 12:17:20 +08:00   ❤️ 2


    https://github.com/vuejs/vue/blob/52719ccab8fccffbdf497b96d3731dc86f04c1ce/src/core/instance/state.js#L121
    https://github.com/vuejs/vue/blob/52719ccab8fccffbdf497b96d3731dc86f04c1ce/src/shared/util.js#L58

    理论上 data 只要是个对象类型就不会报错。
    但是实际工程中,如果传的不是普通对象类型,那么很有可能在传参的时候出现了错误,这样有助于检查代码中可能出现的错误。
    shintendo
        2
    shintendo  
    OP
       2018-09-15 12:31:18 +08:00
    @noe132
    明白了,感谢!
    这句判断和它给的警告有点搭不上啊?
    SilentDepth
        3
    SilentDepth  
       2018-09-15 14:26:40 +08:00
    应该警告 should return plain object?
    shintendo
        4
    shintendo  
    OP
       2018-09-15 14:37:21 +08:00
    @SilentDepth
    因为这里 data 不是 function,所以它提示 data function 返回值不对,我就有点懵
    yangxiongguo
        5
    yangxiongguo  
       2018-09-15 14:49:42 +08:00   ❤️ 1
    调试了一下:
    var _toString = Object.prototype.toString;
    _toString.call(new Date()) 的结果是 "[object Date]",而不是 "[object Object]"
    SilentDepth
        6
    SilentDepth  
       2018-09-15 15:13:58 +08:00
    @shintendo #4 可能 Vue 默认使用者不会错误地使用 new Vue 里的 data ……
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   960 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 20:32 · PVG 04:32 · LAX 13:32 · JFK 16:32
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.