Skip to content

Vue 对象修改属性时watch问题(deep and 深拷贝) #46

Open
@palmerye

Description

export default {
    data () {
        return {
            title: '',
            backgroundColor: '',
            current: {}
        }
    },
    computed: {
    },
    mounted () {
        this.init()
    },
    watch: {
        // 深度 watcher
        current: {
            handler (val, oldVal) {
                if (Object.keys(oldVal).length !== 0) {
                    console.log('触发监听', val)
                }
            },
            deep: true
        }
    },
    methods: {
        init () {
            // 从store里获取state 深拷贝
            let _currentConfig = JSON.parse(JSON.stringify(this.$store.state.chartsConfig.currentConfig))
            // 利用  Object.assign 让新添加的属性具有响应式属性         
            this.current = Object.assign({}, this.current, _currentConfig)
            this.title = this.current.opt.title.text
            this.backgroundColor = this.current.opt.backgroundColor
        },
        changeTitle (val) {
            this.current.opt.title.text = val
        }
    }
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions