单击Vue js可获得单选按钮的值

时间:2019-08-17 11:53:46

标签: javascript vuejs2 radio-button vue-component

我试图创建一个过滤器组件,但首先我希望能够基于所选的单选按钮console.log()过滤器模型的值。

<template>
  <Section>
    <h5>Filter</h5>
    <div class="btn-group" data-toggle="buttons">
      <label class="btn btn-primary active">
        <input type="radio" name="filter" id="all" v-model="filter" value="all" />All
      </label>
      <label class="btn btn-primary">
        <input type="radio" name="filter" id="completed" v-model="filter" value="completed" />Completed
      </label>
      <label class="btn btn-primary">
        <input type="radio" name="filter" id="notcompleted" v-model="filter" value="notcompleted" />Not Completed
      </label>
      <button class="btn btn-primary" @click="consoleFilter">console the value</button>
    </div>
  </Section>
</template>

如果选中了“全部”单选按钮,并且我单击按钮,则我想要的console_log值也必须为“全部”

<script>
export default {
  name: "Filter",
  data() {
    return { filter: null };
  },
  methods: {
    consoleFilter() {
      console.log(this.filter);
    }
  }
};
</script>

有人知道我该怎么做吗?

1 个答案:

答案 0 :(得分:0)

好吧,到目前为止,我的意思是,您正在尝试获取选中按钮的值。只需将onChange事件添加到输入标签即可,如下所示

 <Section>
    <h5>Filter</h5>
    <div class="btn-group" data-toggle="buttons">
      <label class="btn btn-primary active">
        <input type="radio" name="filter" @change="consoleFilter" id="all" v-model="filter" value="all" />All
      </label>
      <label class="btn btn-primary">
        <input type="radio" name="filter" @change="consoleFilter" id="completed" v-model="filter" value="completed" />Completed
      </label>
      <label class="btn btn-primary">
        <input type="radio" name="filter" @change="consoleFilter" id="notcompleted" v-model="filter" value="notcompleted" />Not Completed
      </label>
      <button class="btn btn-primary" @click="consoleFilter">console the value</button>
    </div>
  </Section>

如果您不想这样做,也可以添加观察者作为

watch:{
      filter(value){
        console.log(value)
      }
    }