2017-10-28 237 views
0

我使用V-具有自定义组件V型的自定义组件复选框不工作

Vue.component('lineitem', { 
    template: '#lineitem-template', 
    props: { 
    item: { 
     required: false, 
     default: null 
    }, 
    }, 
    computed: { 
    local_line_item() { 
     console.log("Re computing line item") 
     return _.clone(this.item) 
    }, 
    }, 
    methods: { 
    set_taxable(e) { 
     e.preventDefault(); 

     if (this.local_line_item.taxable == false) { 
     this.local_line_item.taxable = true; 
     } else { 
     this.local_line_item.taxable = false; 
     } 
     console.log("Changing taxable to ", this.local_line_item); 
    }, 
    } 
}); 

与此模板:

<template id="lineitem-template"> 
    <tr> 
    <td> 
     <input type="text" class="form-control" v-model="local_line_item.cost"> 
    </td> 
    <td> 
     <div class="option" @click="set_taxable"> 
     <input type="checkbox" v-model="local_line_item.taxable" v-bind:true-value="true" v-bind:false-value="false"> 
     <label for="check1"></label> 
     </div> 
    </td> 
    </tr> 
</template> 

看到这样的jsfiddle:https://jsfiddle.net/shaunc869/1Ly7mL6n/7/

当我点击复选框我正在更改内部变量的值,但复选框不会更改,我在做什么错误?谢谢!

回答

0

e.preventDefault()里面set_taxable是问题的原因。删除该部分工作得很好。你可以在这里看到更新的提琴:https://jsfiddle.net/1Ly7mL6n/9/

此外,我不明白你的理由使用点击绑定触发set_taxable。由于您已使用v-model绑定来根据复选框的选中状态切换local_line_item.taxable,因此您不需要点击处理程序。所以除非你打算在点击处理程序中做更多的操作,否则你可以删除它。

+0

对不起,我应该有蜜蜂更具体的这一点,基本上我希望能够使用某种其他触发器,以编程方式检查框,我更新了我的小提琴,以显示这一点更清晰。你可以看看更新的小提琴,让我知道你的想法?谢谢! – Shaun

+0

嘿,你没有提供链接到你更新的小提琴。另外,如果你希望以编程方式切换复选框的状态,你可以通过'local_line_item.taxable'来完成,因为它通过'v-model'绑定到复选框。如果可能,你能否详细说明*你想达到什么目的?请阅读[什么是X-Y问题](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem)。 – Nisarg

+0

我很抱歉,我忘了,包括更新的版本号: https://jsfiddle.net/shaunc869/1Ly7mL6n/12 我曾尝试这样做,但是当我改变local_line_item.taxable它没价值” t似乎切换。 – Shaun