如何检测网络组件设置或更改的数据 属性

How to detect data property on web component set or altered

HTML:

<comp-two></comp-two>

JS:

class CompTwo extends HTMLElement {
    constructor() {
        super()
        this._options=[]
    }
    get options() {
        return this._options
    }
    set options(val) {
        this._options = val
    }
}

const el = document.querySelector('comp-two')
el.options = ['one','two','three']

是否有一种可接受的方法来通知 webComponent 中的代码已设置 属性?如果有任何不同,我正在嵌套 Web 组件。

我知道设置一个属性就可以了,但是看起来很浪费?

一个属性可以直接读取:

console.log(this.propertyName)

但由于组件创建后值可能随时更改,问题是要知道何时发生更改,类似于 attributeChangedCallback 用于处理属性更新的方式.

A setter 将在写入命名的 属性 时触发。就像属性的 attributeChangedCallback 一样,属性 的值不一定改变

set propertyName(val){
    this._propertyName = val // keep a copy, name must be different
                             // underscore is popular method
    this.doSomething(val)    // act on the new property value
}

get propertyName(){
    return this._propertyName
}

注意:包含 setter 后,无法再直接读取 属性。使用getter到return由setter保存的本地副本,或者直接读取本地副本。

一分钱终于落在我身上了..