yvl
yvl

Reputation: 670

Listen select option changes in child component, vue.js

Trying to parent's selection option value changes in from child component. And here is the structure.

parent

<child-comp :date="date" />

<select v-model="date">
    <option value="2019-09">2019年9月</option>
    <option value="2019-10">2019年10月</option>
    <option value="2019-11">2019年11月</option>
    <option value="2019-12">2019年12月</option>
    <option value="2020-20">2020年01月</option>
</select>

data(){
    return {
        date: "",
    };
},

Everything is fine up there. changing val, and updating the data prop. But inside the child comp.

child

props: {
    date: String,
},
watch: { 
    date(value){
        console.log(value)
    }
},
computed: {
    dateUpdate(){

        console.log(this.date)

        var dt = new Date(),
            ldt = new Date(dt.getFullYear(), dt.getMonth() + 1, 0),
            y = ldt.getFullYear(),
            m = ("00" + (ldt.getMonth() + 1)).slice(-2),
            d = ("00" + ldt.getDate()).slice(-2),
            result = y + "年" + m + "月" + d + "日";

        return result;
    },
}

I want to listen the date prop, inside the dateUpdate() tried to use watch: still can't console.log the changes... What I am missing?

Upvotes: 0

Views: 818

Answers (1)

JakeHamTexas
JakeHamTexas

Reputation: 51

Your dateUpdate computed property's value is what you should watch for, not the date prop. Currently, you're not changing the value of the prop date, you're just taking a date prop in the child component, and then inside of the dateUpdate computed property you are using the date to return a different value. The name of this different value is dateUpdate, and if you want to see the value change, you should put your watch on this computed property.

child

props: {
    date: String,
},
watch: { 
    dateUpdate(value){
        console.log(value)
    }
},
computed: {
    dateUpdate(){
        ...
    },
}```

Upvotes: 1

Related Questions