【问题标题】:Vue: determine observed object type (distinguish between array and object)Vue:确定观察到的对象类型(区分数组和对象)
【发布时间】:2018-08-25 17:53:06
【问题描述】:

我有一个简单的 Vue 实例:

<html>
  <body>        
    <div id="container">
      <input type="text" id="container" placeholder="enter text" v-model="value">
      <p>{{ value }}</p>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/0.11.10/vue.min.js"></script>
    <script>
      new Vue({
        el: '#container',
        data: {
          value: '',
          list: []
        },
        created: function() {
          console.log(typeof this.list); // i would like to determine type of underlaying object
        }
      });
    </script>
  </body>
</html>

https://codepen.io/anon/pen/KxVQEw?editors=1111

如何确定数据中观察到的属性的类型让我们说 .list 在“已创建”生命周期挂钩中?

【问题讨论】:

    标签: vue.js


    【解决方案1】:

    typeof [] 将返回"object",与typeof {} 相同。如果您想知道它是 JSON 对象还是数组,您可以使用varname.constructor.name

    console.log(typeof []) // object
    console.log([].constructor.name) // Array
    
    console.log(typeof {}) // object
    console.log({}.constructor.name) // Object
    

    在你的情况下:

    console.log(this.list.constructor.name) // Array
    

    【讨论】:

    • 我很惊讶,但它似乎可以像我希望的那样为观察者工作。
    【解决方案2】:

    虽然已经有一个可行的答案,但我决定使用这个替代方案,因为它的代码更少:Array.isArray

    Array.isArray([]) //true
    Array.isArray({}) //false
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-01-02
      • 2019-09-09
      • 2023-01-29
      • 1970-01-01
      • 2017-11-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多