【问题标题】:How to refresh the page after submit form?提交表单后如何刷新页面?
【发布时间】:2020-06-27 15:03:45
【问题描述】:

我在模板中有两个组件,第一个是过滤器,第二个是向 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>

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

【问题讨论】:

  • 在提交回调中使用window.location.reload()。假设它是一个 fetch/axios 调用,你可以把它放在你的 promise 的 then 回调中。话虽如此,您不必刷新页面来更新其他组件的值。最好通过您的商店使用VueX 之类的东西来控制这种行为。或者,我认为你的情况很简单,你可以做this.time = apiCallResponse.time 或任何你的结构。
  • 这是 vue.你不刷新页面,你改变数据。
  • 如何更改发送给请求的数据?因为我是在创建中做的

标签: javascript vue.js


【解决方案1】:

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

在父级中:

<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 here 中的嵌套路由
  2. 您可以使用观察者。由于您想知道 either 是否发生变化,因此您可能希望查看包含它们两者的计算属性。在 AppRequest 组件中输入:computed: { combined() { this.keywords &amp;&amp; this.time} }watch: { combined() { makeApiRequest() } }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-25
    • 1970-01-01
    • 2013-09-21
    • 2013-02-09
    相关资源
    最近更新 更多