programing

Vue: 제출 양식의 응답을 다른 페이지에 표시

prostudy 2022. 3. 20. 12:55
반응형

Vue: 제출 양식의 응답을 다른 페이지에 표시

나는 a를 가지고 있다.<form>vue서버에게 양식을 보내고 JSON 응답을 받아 콘솔에 인쇄한다.그것은 잘 작동한다.

하지만 나는 그 JSON 응답을 받아 다른 페이지에 표시해야 해.예를 들어, 나는 두 개를 가지고 있다..vue파일:GetAnimal.vue그 형태를 가지고 있고 API와 a에서 동물 데이터를 검색한다.DisplayAnimal.vue동물의 데이터를 표시하는 것.동물 반응 데이터에서GetAnimal.vueDisplayAnimal.vue.

Get Animal.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.vue에서/viewanimal끝점:

디스플레이애니멀.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 응답을 통과하면 돼이것이 이것에 접근하는 올바른/좋은 방법인가?

편집:

난 이렇게 해봤어:

겟애니멀에서vue I가 이 데이터를 추가함:

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

그리고 DisplayAnimal에.이것을 부연하다:

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

</script>

그리고 겟애니멀에서도.Vue I는 다음과 같이 덧붙였다.

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

테스트 동물을 디스플레이 구성요소를 사용하여 표시하려고 시도하십시오.하지만 그것은 효과가 없었다 - 나는 빈 페이지를 얻었다.

Vuex를 사용하면 이 문제를 쉽게 해결할 수 있다.

netlify https://m-animalfarm.netlify.app/

github https://github.com/manojkmishra/animalfarm에 있는 코드

여기에 이미지 설명을 입력하십시오.

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>
 <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>

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 }
})

모든 구성 요소에 대해 사용 가능/공유됨

우선 두번째 폴더를 만들어 서비스라고 부르고 service.js를 만들어 당신을 위한 call-good practice와 cleaner code를 전체적으로 만든다.두 번째 사용 vuex. 이런 종류의 데이터는 vuex와 함께 가장 잘 사용된다.

내가 Get Animal을 이해하는 한.vue는 상위 구성 요소이며 하위 구성 요소 DisplayAnimal에 표시하려는 경우그렇다면 소품만 사용하는지 알아보시겠습니까?당신은 또한 같은 정보나 아이에 대한 다른 정보를 $109()를 사용하여 부모에게 다시 보낼 수 있다.상태를 관리하기 위해 vuex를 사용할 것을 강력히 권장함

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>

동물 이름/id를 경로 파라미터로 표시 페이지에 전달하고 해당 구성 요소가 관련 동물 데이터를 가져오고 표시하도록 할 것이다.이는 사용자가 URL을 통해 디스플레이 페이지를 직접 방문하여 불완전한 페이지를 볼 수 있는 상황을 방지한다.

다른 사람들이 지적했듯이 페이지 간에 로컬 상태를 공유하려는 상황에서는 Vuex를 사용하는 것이 좋을 것이다.

편집:

OP에서 요청한 대로 내 답변에 코드를 추가하고 있어.

경로:

const routes = [
  { path: "/", component: SearchAnimals },
  { path: "/viewanimal/:name", component: DisplayAnimal, name: "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>

분명히 이것은 맨 뼈의 예시일 뿐이므로 오류 처리 등을 포함하지는 않지만, 그것은 당신을 일으켜서 실행할 수 있게 해 줄 것이다.

참조URL: https://stackoverflow.com/questions/61988613/vue-display-response-from-form-submit-on-another-page

반응형