1

Hello I'm making a web app using vuex and vue idb. In one of my view I have a table with filter fields. My data are stored using vue-idb and filter fields call applyFilter methods function using the input text box event and the header name of the column's cell

Here is my html

...some html     
<!--columns filters-->
            <tr>
              <td v-if='shownHeaders.length > 0'>
                <input type='checkbox' @change='updateCheckboxList(-1)' :checked='checkAllCheckbox'>
              </td>

              <td v-for='(header,index) in headers' v-if='headers.indexOf(header)>-1'>
                <input @keyup="applyFilter(header,$event )" :disabled="thinking" :placeholder='header +" filter"'>
              </td>
            </tr>

Here is my component

some code ...

applyFilter (header, e) {
      // apply filter after enter key has been pressed
      if (e.keyCode === 13) {
        console.log('Filtering column ' + header + ' with ' + e.target.value)
        // not working unsing dynamical variable, but it does while using static variable like uid
        store.dispatch('tasksSetFilter', {header: e.target.value}) // this doesn't works
        // store.dispatch('tasksSetFilter', {id: e.target.value}) // this works

My issue is that I'm unable to use header variable (a string) as key of dict passed with tasksSetFilter, but if I replace it by a variable having the same name it works.

Is there a way to transform string to variable name to solve my problem?

  • What is `taskSetFilter`? – Bert Sep 06 '17 at 19:06
  • Hello Bert, taskSetFilter refer to idb https://github.com/ddgll/vue-idb/wiki/6-Big-lists and allow you to set filter on task database in my case but task could be replaced by any other db names. – Logan Schwartz Sep 06 '17 at 19:17
  • If I understand correctly, `header` contains a value that you want to be the key for the object you are passing to the action? – Bert Sep 06 '17 at 19:23
  • header is the name of the column so for example it could be 'id'. My issue is that it doesn't work if I replace header by 'id', but it does if I replace it by id – Logan Schwartz Sep 06 '17 at 19:29

1 Answers1

0

Try this:

store.dispatch('tasksSetFilter', {[header]: e.target.value})

What this syntax does is set the parameter to an object where the key will be whatever the value of header is. This is a newer syntax that came about with ES2015.

If you could not support ES2015, you could build the parameter this way:

let filter = {}
filter[header] = e.target.value
store.dispatch('tasksSetFilter', filter)
Bert
  • 80,741
  • 17
  • 199
  • 164
  • it works, thanks. Would it be possible to now what the [] does? – Logan Schwartz Sep 06 '17 at 19:38
  • The brackets just indicate to javascript that it should use the *value* of header as the key to the object you are defining. See this: https://stackoverflow.com/questions/2462800/how-do-i-create-a-dynamic-key-to-be-added-to-a-javascript-object-variable – Bert Sep 06 '17 at 19:40