can't access data variables in watch handler vuejs

前端 未结 2 428
长发绾君心
长发绾君心 2020-12-09 20:17

I\'m trying to set a data variable in a watch handler function for an input field in a VueJs Component. I have something like this:

data() {
    return {
            


        
相关标签:
2条回答
  • 2020-12-09 21:04

    To avoid additional binding, just avoid using the arrow function syntax here.Instead go with ES6 Object shorthands:

    watch: {
        dates: { 
            handler(date) {
                console.log(this.params)
                if (date.start) {
                    this.params.from = moment(date.start, "YYYY/MM/DD")
                }
                if (date.end) {
                    this.params.to = moment(date.end, "YYYY/MM/DD")
                }
            },
            deep: true
        }
    }
    

    Now this will be bound to the correct context by default.

    0 讨论(0)
  • 2020-12-09 21:06

    Let's try bind this to your handler

            handler(date) {
                console.log(this.params)
                if (date.start) {
                    this.params.from = moment(date.start, "YYYY/MM/DD")
                }
                if (date.end) {
                    this.params.to = moment(date.end, "YYYY/MM/DD")
                }
            }.bind(this)
    
    0 讨论(0)
提交回复
热议问题