Vue 3 - 状态不可用且未在 Vue devtools 中显示

Vue 3 - State is not available and is not showing in Vue devtools

我正在学习 Vuejs 3 教程,出于某种原因,在定义我的反应对象后,none 属性可用或在 vue-devtools 中可见。我试图呈现的宠物小精灵名称没有出现,因为宠物小精灵 属性 不可用。有人可以帮我弄清楚发生了什么事吗?下面是我的代码:

HomeView.vue:

<template>
  <div class="home">
    <h3>Hello World!</h3>
      <p>{{number}}</p>
    <ul>
      <li v-for="pokemon in pokemons" :key="pokemon.name" >{{pokemon.name}}</li>
    </ul>
  </div>
</template>

<script>
import axios from "axios";
import { onMounted } from '@vue/runtime-core';
import { reactive } from "vue";
// @ is an alias to /src

export default {
  name: 'HomeView',
  setup(){

    let number = 1;

    const state = reactive({
      pokemons:[],
      urlIdLookup: {}
    })

    onMounted( async () =>{
      try {
          const pokemonReq = await axios.get("https://pokeapi.co/api/v2/pokemon?");
          console.log("data", pokemonReq.data);
          console.log("state", state)
          state.pokemons = pokemonReq.data.results;
      } catch(err){
        console.log(err);
      }
    });

  }
}
</script>

App.vue:

<template>
    <div class="p-14">
      <router-link  class="flex justify-center text-4xl text-yellow-700" to="/">Pokemon Picker</router-link>
    </div>
  <router-view/>
</template>

<style>
</style>

路由器 > index.js


import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'

const routes = [
  {
    path: '/',
    name: 'home',
    component: HomeView
  },
  {
    path: '/about/:slug',
    name: 'about',
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

export default router

您需要 return 来自设置函数的反应数据:

const { onMounted, reactive, toRefs, ref } = Vue;
const app = Vue.createApp({
    setup(){
    let number = ref(1);
    const state = reactive({
      pokemons:[],
      urlIdLookup: {}
    })
    onMounted( async () =>{
      try {
        const pokemonReq = await axios.get("https://pokeapi.co/api/v2/pokemon?");
        state.pokemons = pokemonReq.data.results;
      } catch(err){
        console.log(err);
      }
    });
    return { ...toRefs(state), number }
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.27.2/axios.min.js" integrity="sha512-odNmoc1XJy5x1TMVMdC7EMs3IVdItLPlCeL5vSUPN2llYKMJ2eByTTAIiiuqLg+GdNr9hF6z81p27DArRFKT7A==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<div id="demo">
  <div class="home">
    <h3>Hello World!</h3>
      <p>{{number}}</p>
    <ul>
      <li v-for="pokemon in pokemons" :key="pokemon.name" >{{pokemon.name}}</li>
    </ul>
  </div>
</div>