为什么默认嵌套的Polymer值不起作用?

时间:2017-01-02 05:14:49

标签: polymer

我正在使用最新的2.0-preview版本的Polymer。我想设置默认属性,Polymer文档描述how to do it in Polymer 1.x。我无法在v2.0的此方法中找到任何更改。但它似乎只适用于原始属性而不是对象:

"use strict";

class NewElement extends Polymer.Element {
    static get is() {
        return 'new-element';
    }

    static get config() {
        return {
            properties: {
                user: {
                    // type: Object,  <-- doesn't help anyway

                    firstName: {
                        type: String,
                        value: "John",
                        // observer: '_callObserver'  <-- FYI observers don't work properly too if this usage...
                    },

                    lastName: {
                        type: String,
                        value: "Doe"
                    }
                },
                position: {
                    type: String,
                    value: "Waiter"  // <-- will set a high-level default value properly correctly
                }
            },

            // observers: [
            //    '_callObserver(user.*)'  <-- ...but works using this approach
            // ]
        }
    }

    constructor() {
        super();
        console.dir(this); //  <-- see screenshots below
        // this.user = { firstName: "John", lastName: "Doe" };  <-- works if initialized manually
    }
}

customElements.define(NewElement.is, NewElement);

你可以看到here有一个吸气剂,当我点击它时,我看到user field is undefined

我做错了什么?

1 个答案:

答案 0 :(得分:1)

看起来您正在尝试嵌套属性声明,这是不受支持的。您可以声明包含子属性的对象属性(不是具有typeobserver等的属性声明。)

user属性声明:

properties: {
  user: {
    type: Object,
    firstName: {
      type: String,
      value: "John",
    },
    lastName: {
      type: String,
      value: "Doe"
    }
  },
},

实际上应该是这样的:

properties: {
  user: {
    type: Object,
    value: function() {
      return {
        firstName: "John",
        lastName: "Doe"
      };
    }
  },
},

codepen