Vue,复选框和计算机特性

时间:2017-07-11 11:03:03

标签: javascript vue.js

我正在构建Vue 2应用程序,并且在页面中,我需要跟踪单个复选框的值。所以我这样做了:

<template>
    <div>
        <input
            type="checkbox"
            v-model="checkboxValue"
            /> Check to accept payment <a href="url" target="_blank">terms and conditions</a>
    </div>
</template>

<script>
export default {
    props: {
        cardData: {
            type: Object,
            required: true,
        },
        eventBus: {
            type: Object,
            required: true,
        },
        url: {
            type: String,
            required: true,
        },
    },
    data() {
        return {
            checkboxValue: false,
        };
    },
    computed: {
        forwardCheckboxValue() {
            console.log(this.checkboxValue);
            this.eventBus.$emit("checkbox_value", {
                checkboxValue: this.checkboxValue,
            });
        },
    },
};
</script>

<style>
</style>

基本上我想跟踪是否选中了复选框,每次更改值时我想发出一个警告我的事件。

问题是不会触发计算属性中的console.log。 我错过了什么?

1 个答案:

答案 0 :(得分:1)

您可以使用computed setter并从checkboxValue选项中删除data。这是fiddle

computed:{
    checkboxValue:{
        get(){
            return false;
        },
        set(newValue){
            this.$emit('checkbox-changed', newValue);
        }
    }
}

或者坦诚的教务长建议设置一个watcher,其名称应与您正在观看的data属性相同。这是fiddle

watch:{
    checkboxValue(newValue){
        this.$emit('checkbox-changed', newValue);
    }
} 
相关问题