如何在VUE.js中将** newCat = $ event.target.value **表达式从** input **传递到** method **?

时间:2019-04-16 13:40:51

标签: javascript vue.js

在VUE.js中如何将此表达式 newCat = $ event.target.value 输入转移到方法,仅保留< 输入中的strong> newCat 。然后在vuex中使用它。像这样@ input =“ newCat”

    <f7-list form>
        <f7-list-input
          :value="newCat"
          @input="newCat = $event.target.value"
          type="text"
          placeholder="some item"
        ></f7-list-input>
        <f7-button fill color="blue" @click="addCat">Add some</f7-button>
    </f7-list>


data() {
    return{
        cats:[],
        newCat: null
  }
},
mounted() {
  if (localStorage.getItem('cats')) {
    try {
      this.cats = JSON.parse(localStorage.getItem('cats'));
    } catch(e) {
      localStorage.removeItem('cats');
    }
  }
},
methods: {
  addCat() {
    if (!this.newCat) {
      return;
    }
    this.cats.push(this.newCat);
    this.newCat = '';
    this.saveCats();
  },
  removeCat(x) {
    this.cats.splice(x, 1);
    this.saveCats();
  },
  saveCats() {
    const parsed = JSON.stringify(this.cats);
    localStorage.setItem('cats', parsed);
  }
}
}

1 个答案:

答案 0 :(得分:1)

尝试一下:

<template>
  <f7-list form>
      <f7-list-input
        :value="newCat"
        @input="newCatOnInput"
        type="text"
        placeholder="some item"
      ></f7-list-input>
      <f7-button fill color="blue" @click="addCat">Add some</f7-button>
  </f7-list>
</template>

<script>
export default {
  data() {
    return{
      cats:[],
      newCat: null
    };
  },
  mounted() {
    if (localStorage.getItem('cats')) {
      try {
        this.cats = JSON.parse(localStorage.getItem('cats'));
      } catch(e) {
        localStorage.removeItem('cats');
      }
    }
  },
  methods: {
    addCat() {
      if (!this.newCat) {
        return;
      }
      this.cats.push(this.newCat);
      this.newCat = '';
      this.saveCats();
    },
    removeCat(x) {
      this.cats.splice(x, 1);
      this.saveCats();
    },
    saveCats() {
      const parsed = JSON.stringify(this.cats);
      localStorage.setItem('cats', parsed);
    },
    newCatOnInput(e) {
      this.newCat = e.target.value;
    }
  }
}
</script>