Vue搜索过滤器复选框问题

时间:2019-03-01 09:04:54

标签: javascript vue.js

我对数组的复选框和vue过滤器有疑问。

new Vue({
  el: "#app",
  data: {
    todos: [
      { text: "Learn JavaScript"},
      { text: "Learn Vue"},
      { text: "Play around in JSFiddle"},
      { text: "Build something awesome"}
    ],
    search: '',
  },
  methods: {
  	
  },
  computed: {
  	filtered() {
      return this.todos.filter(todo => {
        return todo.text.toLowerCase().includes(this.search.toLowerCase())
      })
    },
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input type="text" v-model="search">
  <ol>
    <li v-for="todo in filtered">
      <label>
        <input type="checkbox">

        <del v-if="todo.done">
          {{ todo.text }}
        </del>
        <span v-else>
          {{ todo.text }}
        </span>
      </label>
    </li>
  </ol>
</div>

如果您首先从数组中检查并搜索其他任何内容:

检查->学习javascript

搜索->学习Vue

Vue似乎已被检查。

应该那样工作吗?

如何从显示的列表中删除所有内容并同时添加?

2 个答案:

答案 0 :(得分:3)

使用v-model绑定到filtered数组中

new Vue({
  el: "#app",
  data: {
    todos: [
      { text: "Learn JavaScript"},
      { text: "Learn Vue"},
      { text: "Play around in JSFiddle",done:true},
      { text: "Build something awesome"}
    ],
    search: '',
  },
  methods: {
  	
  },
  computed: {
  	filtered() {
      return this.todos.filter(todo => {
        return todo.text.toLowerCase().includes(this.search.toLowerCase())
      })
    },
  }
})
body {
  background: #20262E;
  padding: 20px;
  font-family: Helvetica;
}

#app {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  transition: all 0.2s;
}

li {
  margin: 8px 0;
}

h2 {
  font-weight: bold;
  margin-bottom: 15px;
}

del {
  color: rgba(0, 0, 0, 0.3);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <input type="text" v-model="search">
  <ol>
    <li v-for="todo in filtered">
      <label>
        <input v-model="todo.done" type="checkbox">
          <del v-if="todo.done">{{ todo.text }}</del>
          <span v-if="!todo.done">{{ todo.text }}</span>
          
      </label>
    </li>
  </ol>
</div>

默认情况下,此处选中Play around in JSFiddle

答案 1 :(得分:0)

只需在待办事项中添加done: false,然后在v-model="todo.done"中添加v-for即可输入。

Example on JSFiddle

与您的代码不同:

// added `done`
todos: [
  { done: false, text: "Learn JavaScript"},
  { done: false, text: "Learn Vue"},
  { done: false, text: "Play around in JSFiddle"},
  { done: false, text: "Build something awesome"}
]
<!-- added `v-model="todo.done"` -->
<input v-model="todo.done" type="checkbox">