首页 > 解决方案 > 提交表单后如何刷新页面?

问题描述

我在模板中有两个组件,第一个是过滤器,第二个向 API 发出请求。我想知道在提交第一个(过滤器)后是否可以刷新第二个组件(请求)的值

在主页中,请求具有默认值,如果用户使用过滤器,则请求必须更改为用户插入的值

<template>
<app-filter></app-filter>
<app-request :time="time" :keyword=keyword />
</template>

<script>
export default {
  components:{
        "app-request": Request,
        "app-filter": Filter
    },
  data() {
        return {
            keyword: "Hello",
            time:"today",
        }
    }
  }
</script>

过滤器会改变关键字和时间的默认值

<template>
<form @submit.prevent="submit">
<input v-model="keyword" class="input" type="text">
<input v-model="time" class="input" type="text">
<button type="submit">send</button>
</form>
</template>

<script>
export default {
  data() {
        return {
            time:"",
            keyword: "",
        }
    },
    methods:{
        submit(){
          //what i do here to change the value in request?
        }
    },
}
</script>

请求将显示来自 API 的值,请求页面将从主页面接收道具

<template>
<div :time="time"></div>
</template>

<script>
export default {
  props:[
        'keywords',
        'time',
  ],
  create(){
    //make a request to api, here is ok
  }
}
</script>

在过滤器组件中提交表单后如何刷新主页?

标签: javascriptvue.js

解决方案


一种简单的方法是让父级处理与某些事件的通信。

在父级中:

<app-filter @applied="filtersApplied"></app-filter>

methods: {
  filtersApplied (filters) {
    this.keyword = filters.keyword
    this.time = filters.time
  }
}

在 AppFilter 组件中:

submit () {
  this.$emit('applied', { keyword: this.keyword, time: this.time })
}

编辑 我注意到你在谈论你是如何在 created() 中进行调用的。也有几个解决方案。

  1. 您可以使用子组件/嵌套路由,因此在提交时将它们作为查询参数添加到 URL,这将导致组件重新加载并再次调用 created()。在此处查看 Router api 中的嵌套路由
  2. 你可以使用观察者。由于您想知道其中任何一个是否发生变化,您可能希望查看包含它们两者的计算属性。在 AppRequest 组件中放置:computed: { combined() { this.keywords && this.time} }watch: { combined() { makeApiRequest() } }

推荐阅读