在Vue中向对象添加对象

时间:2018-03-13 20:57:42

标签: javascript html vue.js

我无法将对象添加到数组中。

这是我使用的脚本:

<script>
export default {
  name: 'pokemon',
  data(){
    return{
      pokemon: [
        {name: "Bulbasaur", number: "001"},{name: "Ivysaur", number: "002"},{name: "Venusaur", number: "003"},
        {name: "Charmander", number: "004"},{name: "Charmeleon", number: "005"},{name: "Charizard", number: "006"},
        {name: "Squirtle", number: "007"},{name: "Wartortle", number: "008"},{name: "Blastoise", number: "009"},
        {name: "Pikachu", number: "025"}, {name: "Mewtwo", number: "150"}
      ],
      selected:'',
      seen: false
    }
  },
  methods: {
    addPokemon(){
        var name = document.getElementById('pokeName').value;
        var number = document.getElementById('pokeNum').value;
        var pokeSON = "{name: \"" + name + "\", number: \"" + number + "\"}";

        this.pokemon.push(pokeSON);
    }
  },
}

</script>

我从中提取姓名和号码:

<input type="text" placeholder="Pokémon Name" id="pokeName">
<input type="number" placeholder="3 digit Poké Number" id="pokeNum">
<button v-on:click="addPokemon">Add Pokémon</button>

当我点击按钮时,它会在我的列表中添加一个未定义的对象。有什么想法让我指出正确的方向吗?

1 个答案:

答案 0 :(得分:0)

你需要推送一个实际的对象,而不是一个字符串。

&#13;
&#13;
addPokemon(){
        var name = document.getElementById('pokeName').value;
        var number = document.getElementById('pokeNum').value;
        var pokeSON = {name: name, number: number};

        this.pokemon.push(pokeSON);
    }
&#13;
&#13;
&#13;