Javascript Vue:在另一页上显示来自表单提交的响应

Javascript Vue:在另一页上显示来自表单提交的响应,javascript,json,vue.js,vuejs2,Javascript,Json,Vue.js,Vuejs2,我在vue中有一个。我将该表单发送到服务器,获取JSON响应,并将其打印到控制台。它很好用 但是,我需要获取JSON响应并将其显示在另一个页面上。例如,我有两个.vue文件:GetAnimal.vue,它具有从API检索动物数据的表单和显示动物数据的DisplayAnimal.vue。我需要将响应动物数据从GetAnimal.vue定向到DisplayAnimal.vue GetAnimal.vue: <template> <form v-on:submit.prevent=

我在
vue
中有一个
。我将该表单发送到服务器,获取JSON响应,并将其打印到控制台。它很好用

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

GetAnimal.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>
<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>
现在我想把这个JSON给
/viewanimal
端点处的
DisplayAnimal.vue

DisplayAnimal.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>
<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>
并在DisplayAnimal.vue中执行以下操作:

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

</script>

尝试使用显示组件显示该试验动物。然而,它只是不起作用-我得到了一个空页面。

首先,创建第二个文件夹call it services和create service.js for you axios call-良好的实践和更干净的代码。 第二,使用vuex。这种数据最好与vuex一起使用

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

Vue.component(“产品”{
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>
道具:{ 信息:{ 类型:字符串, 要求:正确, 默认值:Hi } }, 模板:{{message}}`, 数据(){…} }) //axios调用的另一个组件中的html就在这个组件中//
我会将动物名称/id作为路由参数传递到显示页面,并让该组件负责获取和显示相关动物数据。这避免了用户可以通过URL直接访问显示页面并看到不完整页面的情况

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

编辑:

根据OP的要求,我在我的答案中添加了一些代码

路线:

DisplayAnimal.vue:


动物名称:{{Animal.name}

毛发颜色:{{animal.furColor}}

人口:{{动物.人口}

已灭绝:{animal.isExtinct}

是驯化的:{animal.isDomesticated}

从“axios”导入axios; 导出默认值{ 名称:“展示动物”, 数据:()=>({ 动物:{} }), 方法:{ 动物(名称){ axios .得到(`http://localhost:8088/animalsapi?animal=${name}`) 。然后(响应=>{ this.animal=response.data; }); } }, 创建(){ this.fetchAnimal(this.route.params.name); } };
SearchAnimals.vue:


得到动物
导出默认值{
名称:“搜索动物”,
数据:()=>({
动物:“
}),
方法:{
onSubmit(){
这是$router.push({
名称:“展示动物”,
参数:{name:this.animal}
});
}
}
};

显然,这是一个简单的示例,因此不包含任何错误处理等,但它应该可以帮助您启动并运行。

使用Vuex,您可以轻松解决此问题

netlify的工作示例

github上的代码

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

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

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 }
})
状态对所有组件可用/共享

您能给我看一些代码吗?不,
GetAnimal.vue
到目前为止没有连接到
DisplayAnimal.vue
-我拥有的代码就是我发布的代码。为什么会是父母?我考虑的是MVC模型,其中
GetAnimal.vue
既是控制器又是模型:表单获取用户的输入并更新模型(动物信息:
this.info
)。现在只需将该信息传递到视图
DisplayAnimal.vue
。我来自Java,在Java应用程序中,我没有看到视图类扩展模型/控制类-这种关系通常是一种组合关系,而不是继承关系。那么你想做什么?为了在vue中从一个组件向另一个组件显示数据,请使用vuex或使用道具传递数据(从父级传递到子级,或者您可以称之为兄弟级),即使使用道具也是如此。VUEJ中总共有3个选项,根据您的需要都很好1-使用道具从父级到子级共享数据,2-发送自定义事件以从子级到父级共享数据,3-使用Vuex创建应用程序级共享状态。如何将
消息
值传递给该组件?我已经读过关于道具的内容,但是我不知道如何将道具值从
GetAnimal.vue
分配到
DisplayAnimal.vue
。您在其中编写“道具”的组件是接收组件,如上所示,您通过v-bind vue从另一个组件发送道具。组件('storage',{data:{return message message={},//说它通过axios call获取数据)},…..})当你想展示它时,你想告诉同一个产品组件它将要得到一些道具//你也可以使用速记:message=“message”`存储告诉产品组件它发送带有消息名称的消息prop,并在产品组件内部指定props了解基本知识,了解vue.data(){return{…}后再学习vuex状态}注意到这样保存数据的正确方法是使用Vuex状态,而不是
$router。将表单输入(作为查询)推送到接收组件并在那里调用API?否则,我必须同意这里的其他人的看法,这最好是用Vuex来完成。如果您想要快速解决方案,可以
localStorage.s
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>
const routes = [
  { path: "/", component: SearchAnimals },
  { path: "/viewanimal/:name", component: DisplayAnimal, name: "displayAnimal" }
];
<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>
<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>
 <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>
<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>
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   );  
    },     
  }
  }
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 }
})