从另一个使用Vue的组件中使用链接获取ID。

huangapple go评论69阅读模式
英文:

Get the id From another component with the Link using Vue

问题

以下是您要翻译的内容:

PokeList 组件

<div class="row">
  <div v-for="pokemon in pokemons" :key="pokemon.id" class="col-12 col-md-4 col-sm-6">
    <div class="card-image">
      <div class="card-sl">
        <router-link :to="'/pokemon/' + pokemon.id">
          <img :src="pokemon.sprites.front_default" @click="redirectToDescription(pokemon.id)" />
        </router-link>
      </div>
      <div class="card-heading">
        <h3 class="pokemonName">{{ pokemon.name }}</h3>
      </div>
      <div class="card-text">
        <p>Base Experience: {{ pokemon.base_experience }}</p>
      </div>
    </div>
  </div>
</div>
<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';

export default {
  name: "App",
  data() {
    return {
      pokemons: [],
    };
  },
  setup() {
    const pokemons = ref([]);
    onMounted(async () => {
      try {
        for (let index = 1; index < 152; index++) {
          const response = await axios.get(`https://pokeapi.co/api/v2/pokemon/${index}`);
          console.log(response.data);
          pokemons.value.push(response.data);
        }
      } catch (error) {
        console.error(error);
      }
    });
    return {
      pokemons
    };
  },
  methods: {
    redirectToDescription(pokemonId) {
      this.$router.push('/pokemon/' + pokemonId);
    }
  }
};
</script>

Describe 组件

<template>
  <div>
    <h2>Pokemon Description</h2>
    <p>{{ this.$route.params.id }}</p>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';

export default {
  name: "App",
  data() {
    return {
      pokemons: [],
    };
  },
  setup() {
    const pokemons = ref([]);
    onMounted(async () => {
      try {
        const pokemonId = this.$route.params.id;
        const response = await axios.get(`https://pokeapi.co/api/v2/pokemon/${pokemonId}`);
        console.log(response.data);
        pokemons.value.push(response.data);
        console.log(pokemonId);
      } catch (error) {
        console.error(error);
      }
    });
    return {
      pokemons
    };
  }
};
</script>

请注意,我只翻译了代码部分,没有包括问题中的其他内容。如果您需要进一步的帮助,请随时提问。

英文:

I'm making a project with the PokeAPI using vue, I have 3 components, 1. Home(Just a Welcome Page without js), 2. Pokelist(calls the API and shows the first 151 Pokemon), 3. Details (THe one where I want to show the details of the selected Pokemon), I have to use RouterLink.
I am clueless about doing something like this and found out a way of send the id of the selected Pokemon into the "Description" component's link (Bulbasaur puts a "1" at the end of the link for instance) the thing is that I can't get that id into the API call bit I can display it in an h3 for example.
I don't know another way of getting the id from the pokeList component in the Description component to get only that Pokemon information using router link, I'm a beginner Here is my Pokelist code:

PokeList Component

&lt;div class=&quot;row&quot;&gt;
&lt;div v-for=&quot;pokemon in pokemons&quot; :key=&quot;pokemon.id&quot; class=&quot;col-12 col-md-4 col-sm-6&quot;&gt;
&lt;div class=&quot;card-image&quot;&gt;
&lt;div class=&quot;card-sl&quot;&gt;
&lt;router-link :to=&quot;&#39;/pokemon/&#39; + pokemon.id&quot;&gt;
&lt;img :src=&quot;pokemon.sprites.front_default&quot; @click=&quot; redirectToDescription(pokemon.id)&quot; /&gt;
&lt;/router-link&gt; &lt;!--This sends you to the new component with the selected pokemon Id at the end--&gt;
&lt;/div&gt;
&lt;div class=&quot;card-heading&quot;&gt;
&lt;h3 class=&quot;pokemonName&quot;&gt;{{ pokemon.name }}&lt;/h3&gt;
&lt;/div&gt;
&lt;div class=&quot;card-text&quot;&gt;
&lt;p&gt;Base Experience: {{ pokemon.base_experience }}&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;script&gt;
import { ref, onMounted } from &#39;vue&#39;;
import axios from &#39;axios&#39;;
export default {
name: &quot;App&quot;,
data() {
return {
pokemons: [],
};
},
setup() {
const pokemons = ref([]);
onMounted(async () =&gt; {
try {
for (let index = 1; index &lt; 152; index++) {
const response = await axios.get(`https://pokeapi.co/api/v2/pokemon/${index}`);
console.log(response.data);
//console.log(response.data.moves);
pokemons.value.push(response.data); // Push each Pokemon data to the reactive array
}
}
catch (error) {
console.error(error);
}
});
return {
pokemons
};
},
methods: {
redirectToDescription(pokemonId) {
this.$router.push(&#39;/pokemon/&#39; + pokemonId);
}
}
};
&lt;/script&gt;

Now, in the new component i try to get that id number from the link but it throws an error "TypeError: Cannot read properties of undefined (reading '$route')"

Describe Component


&lt;template&gt;
&lt;div&gt;
&lt;h2&gt;Pokemon Description&lt;/h2&gt;
&lt;p&gt;{{ this.$route.params.id }}&lt;/p&gt; &lt;!--This is the only way i found to get the id and here it works--&gt;
&lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
import { ref, onMounted } from &#39;vue&#39;;
import axios from &#39;axios&#39;;
export default {
name: &quot;App&quot;,
data() {
return {
pokemons: [],
};
},
setup() {
const pokemons = ref([]);
onMounted(async () =&gt; {
try {
const pokemonId = this.$route.params.id;
const response = await 
//Here, i try to use the method to get the id biut i get the said error, if i just put a number it works but it needs to throw the previously selected pokemon id to get all the info of that specific pokemon
axios.get(`https://pokeapi.co/api/v2/pokemon/${pokemonId}`); 
console.log(response.data);
//console.log(response.data.moves);
pokemons.value.push(response.data); // Push each Pokemon data to the reactive array
console.log(pokemonId);
}
catch (error) {
console.error(error);
}
});
return {
pokemons
};
}
};
&lt;/script&gt;

答案1

得分: 0

在描述组件中遇到的错误是因为您尝试在setup()函数内部直接访问$route。在Vue 3中,包括setup()函数在内的组合API无法访问实例的属性和方法,如$route

要在组合API组件中访问路由信息,您可以使用vue-router包中的useRoute函数。以下是如何修改您的描述组件以从路由中获取id参数的方式:

<template>
  <div>
    <h1>Details</h1>
    <div v-for="pokemon in pokemons" :key="pokemon.id">
      <h3>{{ pokemon.name }}</h3>
      <!-- 显示Pokemon的其他详细信息 -->
    </div>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue';
import axios from 'axios';
import { useRoute } from 'vue-router';

export default {
  name: "Describe",
  setup() {
    const pokemons = ref([]);
    const route = useRoute();

    onMounted(async () => {
      try {
        const pokemonId = route.params.id;
        const response = await axios.get(`https://pokeapi.co/api/v2/pokemon/${pokemonId}`);
        pokemons.value.push(response.data);
        console.log(response.data);
      } catch (error) {
        console.error(error);
      }
    });

    return {
      pokemons
    };
  }
};
</script>

在这个更新后的代码中,我们从vue-router中导入了useRoute函数,然后在setup()函数内调用它以获取当前路由信息。我们将其赋值给了route常量。从route.params.id中,我们提取了通过URL传递的id参数。

现在,您可以在axios调用中访问id参数并检索特定Pokemon的详细信息。获取的数据随后被推送到pokemons数组中,您可以在模板中迭代该数组以显示Pokemon的详细信息。

英文:

The error you're encountering in the Describe component is because you're trying to access $route directly within the setup() function. In Vue 3, the composition API, including the setup() function, doesn't have access to the instance's properties and methods like $route.

To access route information in a composition API component, you can use the useRoute function from the vue-router package. Here's how you can modify your Describe component to get the id parameter from the route:

&lt;template&gt;
&lt;div&gt;
&lt;h1&gt;Details&lt;/h1&gt;
&lt;div v-for=&quot;pokemon in pokemons&quot; :key=&quot;pokemon.id&quot;&gt;
&lt;h3&gt;{{ pokemon.name }}&lt;/h3&gt;
&lt;!-- Display other details of the Pokemon --&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
import { ref, onMounted } from &#39;vue&#39;;
import axios from &#39;axios&#39;;
import { useRoute } from &#39;vue-router&#39;;
export default {
name: &quot;Describe&quot;,
setup() {
const pokemons = ref([]);
const route = useRoute();
onMounted(async () =&gt; {
try {
const pokemonId = route.params.id;
const response = await axios.get(`https://pokeapi.co/api/v2/pokemon/${pokemonId}`);
pokemons.value.push(response.data);
console.log(response.data);
} catch (error) {
console.error(error);
}
});
return {
pokemons
};
}
};
&lt;/script&gt;

In this updated code, we import the useRoute function from vue-router and then call it within the setup() function to get the current route information. We assign it to the route constant. From route.params.id, we extract the id parameter that was passed in the URL.

Now, you can access the id parameter in your axios call and retrieve the details of the specific Pokemon. The fetched data is then pushed to the pokemons array, which you can iterate over in the template to display the Pokemon's details.

huangapple
  • 本文由 发表于 2023年6月12日 05:36:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/76452595.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定