5

我有一个<form>vue. 我将该表单发送到服务器,获取 JSON 响应,然后将其打印到控制台。它工作正常。

但是,我需要获取该 JSON 响应并将其显示在另一个页面上。例如,我有两个.vue文件:GetAnimal.vue一个具有表单并从 API 检索动物数据,一个DisplayAnimal.vue显示动物数据。我需要将响应动物数据从 定向GetAnimal.vueDisplayAnimal.vue

获取动物.vue

<template>
 <form v-on:submit.prevent="getAnimal()">
  <textarea v-model = "animal"
      name = "animal" type="animal" id = "animal"
      placeholder="Enter your animal here">
  </textarea>

  <button class = "custom-button dark-button"
      type="submit">Get animal</button>
 </form>
</template>
<script>
    import axios from 'axios';

    export default {
        name: 'App',
        data: function() {
            return {
                info: '',
                animal: ''
            }
        },
        methods:  {
            getAnimal: function()  {
                 axios
                    .get('http://localhost:8088/animalsapi?animal=' + this.animal)
                    .then(response => (this.info = response.data));
                 console.log(this.info);
            }
        }
    }
</script>

响应:检索带有动物数据的 JSON,如下所示:

{
"fur-color": "yellow",
"population": 51000,
"isExtinct": false,
"isDomesticated": true
}

我现在想将该 JSON 提供给DisplayAnimal.vueat/viewanimal端点:

DisplayAnimal.vue

<template>
  <div>
    <p>Animal name: {{animal}}}</p>
    <p>Fur color: {{furColor}}</p>
    <p>Population: {{population}}</p>
    <p>Is extinct: {{isExtinct}}</p>
    <p>Is domesticated: {{isDomesticated}}</p>
  </div>
</template>

我该怎么做?我知道我可以通过 重定向this.$router.push({ path });,但我只将它用于导航,而这里需要传递 JSON 响应。这甚至是解决此问题的正确/良好做法吗?

编辑

我试过这个:

GetAnimal.vue我添加了这些数据:

data: function() {
   return {
     animal:  {
       name: 'Cat',
       furColor: 'red',
       population: '10000',
       isExtinct: false,
       isDomesticated: true
}

DisplayAnimal.vue中:

<script>
    export default  {
        props:  {
            animal:  {
                name: {
                    type: String
                },
                furColor:  {
                    type: String
                },
                population: String,
                isExtinct: String,
                isDomesticated: String
            }
        }
    }

</script>

GetAnimal.vue我添加了这个:

methods: {
            animals: function()  {
                alert("animals");
                this.$router.push({name: 'viewanimal',
                                query: {animal: JSON.stringify(this.animal)}});
            },

尝试使用显示组件显示该测试动物。但是它只是没有用 - 我得到一个空页面。

4

4 回答 4

5

使用Vuex,你可以轻松解决这个问题

netlify 上的工作示例 https://m-animalfarm.netlify.app/

github 上的代码 https://github.com/manojkmishra/animalfarm

在此处输入图像描述

GetAnimal.vue(我已禁用 axios 调用以进行测试和硬编码信息)

 <template>
 <form v-on:submit.prevent="getAnimal()">
   <textarea v-model = "animal" name = "animal" type="animal" id = "animal"
   placeholder="Enter your animal here">
  </textarea>
  <button class = "custom-button dark-button"
  type="submit">Get animal</button>
  </form>
 </template>
 <script>
 import axios from 'axios';
 export default 
 {
    name: 'App',
    data: function() {  return { info: '', animal: ''  }  },
    methods:  {
        getAnimal: function()  {
            // axios
            //   .get('http://localhost:8088/animalsapi?animal=' + this.animal)
             //   .then(response => (this.info = response.data),
                this.info={"fur-color": "yellow","population": 51000,"isExtinct":     
                            false,"isDomesticated": true },
                this.$store.dispatch('storeAnimals', this.info)
                //);
        }
    }
 }
 </script>

DisplayAnimal.vue

<template>
<div>
<p>Animal name: {{stateAnimal.animal}}</p>
<p>Fur color: {{stateAnimal.furColor}}</p>
<p>Population: {{stateAnimal.population}}</p>
<p>Is extinct: {{stateAnimal.isExtinct}}</p>
<p>Is domesticated: {{stateAnimal.isDomesticated}}</p>
 </div>
</template>
<script>
 import {mapState, mapGetters} from 'vuex';
export default {
computed:{  ...mapState({ stateAnimal:state => state.modulename.stateAnimal }),   
 },
}
</script>

modulename.js(存储模块)

export default
{
 state: {stateAnimal:null,  },
 getters:{ },
 mutations: 
 {    ['STORE_ANIMALS'] (state, payload) 
    {  state.stateAnimal = payload;  
    console.log('state=',state)
   },

  },
 actions: 
 {  storeAnimals: ({commit}, data) => 
    { console.log('storeanim-data-',data);
      commit(  'STORE_ANIMALS', data   );  
    },     
  }
  }

Index.js(用于 vuex 存储),如果页面刷新,您可以禁用持久状态作为保存状态

import Vue from 'vue'
import Vuex from 'vuex'
import modulename from './modules/modulename'
import createPersistedState from "vuex-persistedstate";

Vue.use(Vuex)
export default new Vuex.Store({
plugins: [createPersistedState({ storage: sessionStorage })],
state: {  },
mutations: {  },
actions: {  },
modules: { modulename }
})

状态对所有组件都可用/共享 在此处输入图像描述

于 2020-05-28T03:36:18.957 回答
1

首先创建第二个文件夹,将其命名为 services 并为您的 axios 调用创建 service.js - 良好的实践和更简洁的代码。第二次使用vuex。这种数据最好与 vuex 一起使用。

据我了解 GetAnimal.vue 是父组件,您希望在子组件 DisplayAnimal.vue 中显示它。如果是这样,你想看看这是否有效,只需使用道具。您还可以使用 $emit() 将孩子的相同信息或任何其他信息发送回父母。强烈建议使用 vuex 来管理状态

于 2020-05-24T18:44:52.663 回答
1
Vue.component('product',{
  props:{
    message:{
      type:String,
      required:true,
      default:'Hi.'
    }
  },
  template:`<div>{{message}}</div>`,
  data(){...}
})

//html in the other component you axios call is in this component //<product meesage="hello"></product>
于 2020-05-25T09:02:10.480 回答
1

我会将动物名称/id 作为路由参数传递给显示页面,并让该组件负责获取和显示相关的动物数据。这避免了用户可以直接通过 URL 访问显示页面并看到不完整页面的情况。

在您想在页面之间共享本地状态的情况下,正如其他人指出的那样,您可能想要使用Vuex

编辑:

我正在按照 OP 的要求在我的答案中添加一些代码。

路线:

const routes = [
  { path: "/", component: SearchAnimals },
  { path: "/viewanimal/:name", component: DisplayAnimal, name: "displayAnimal" }
];

DisplayAnimal.vue:

<template>
  <div>
    <p>Animal name: {{animal.name}}</p>
    <p>Fur color: {{animal.furColor}}</p>
    <p>Population: {{animal.population}}</p>
    <p>Is extinct: {{animal.isExtinct}}</p>
    <p>Is domesticated: {{animal.isDomesticated}}</p>
  </div>
</template>

<script>
import axios from "axios";

export default {
  name: "DisplayAnimal",
  data: () => ({
    animal: {}
  }),
  methods: {
    fetchAnimal(name) {
      axios
        .get(`http://localhost:8088/animalsapi?animal=${name}`)
        .then(response => {
          this.animal = response.data;
        });
    }
  },
  created() {
    this.fetchAnimal(this.$route.params.name);
  }
};
</script>

搜索动物.vue:

<template>
  <form v-on:submit.prevent="onSubmit">
    <textarea
      v-model="animal"
      name="animal"
      type="animal"
      id="animal"
      placeholder="Enter your animal here"
    ></textarea>
    <button type="submit">Get animal</button>
  </form>
</template>

<script>
export default {
  name: "SearchAnimal",
  data: () => ({
    animal: ""
  }),
  methods: {
    onSubmit() {
      this.$router.push({
        name: "displayAnimal",
        params: { name: this.animal }
      });
    }
  }
};
</script>

显然这是一个简单的例子,所以不包含任何错误处理等,但它应该让你启动并运行。

于 2020-05-27T09:21:09.243 回答