传递复选框 true 或 false VueJS

时间:2021-05-02 12:47:32

标签: vue.js

我的 VueJS 站点上有一个复选框,我想执行以下操作:如果复选框 special 为真,则在列中发送数据库值 1,我该如何正确执行此操作?

我喜欢这个:

<label class="checkbox-control">
  <input type="checkbox" v-model="special"  v-on:change="special"  :disabled="channel.length === 0">

  <div class="checkbox-control__content"><i></i>Test</div>
</label>

data() {
    return {
      channel: "",
      special: false,
    }
    sendFunction() {
      this.$root.axios.post("/user/userPromo", {
        channel: this.channel,
        special: this.special
      }).then((res) => {
        const data = res.data;
        this.$root.showNotify(data.type, this.$t(`index.${data.message}`, {
          name: data.name
        }));
      });
    },

在后端,当我在表中添加数据时,我使用 $special = $r->get('special');,但它不想工作。我什么时候出错了?

1 个答案:

答案 0 :(得分:1)

您可以使用:true-value="1" false-value="false"

<input type="checkbox" v-model="toggle" true-value="1" false-value="false" />

// when checked:
vm.toggle === '1'
// when unchecked:
vm.toggle === 'false'

Vue2 和 Vue3:

https://v3.vuejs.org/guide/forms.html#checkbox-2

https://vuejs.org/v2/guide/forms.html#Checkbox

然后在 this.special methods 中使用 sendFunction

var app = new Vue({
  el: '#app',
  data: {
    special: false
  },
  methods: {
    sendFunction: function(event) {
    
      console.log(this.special)
      
      //this.$root.axios.post("/user/userPromo", {
        //channel: this.channel,
        //special: this.special
      //}).then((res) => {
        //const data = res.data;
        //this.$root.showNotify(data.type, this.$t(`index.${data.message}`, {
          //name: data.name
        //}));
      //});
    }  
  }
})
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.12/dist/vue.js"></script>
<div id="app">
  <input type="checkbox" v-model="special" v-on:change="sendFunction" true-value="1" false-value="false">
</div>

此外,如果 this.special 在 axios 中不可用,则意味着 this 将绑定到 axios 函数,因此您需要先保存数据并将其用作保存变量:

 sendFunction: function(event) {
        const value = this.special      
          this.$root.axios.post("/user/userPromo", {
          //use value here