使用浏览器后退按钮查看Vue.js状态历史记录

3

我正在使用Vue和Laravel开发一个应用程序。Laravel控制着我的路由,我没有使用vue-router

根据父组件数据对象的状态,我有时会有条件地加载一些组件。

我在父组件中有这个方法:

  activateListingForm: function() {
    this.listingFormActive = !this.listingFormActive;
  }

这个方法是由一个按钮触发的,该按钮将把 this.listingFormActive 更改为 true 或 false。

然后我在组件的模板中有如下内容:

  <transition name="slide-fade">
    <create-listing-form v-if="listingFormActive"></create-listing-form>
    <listings-table v-else></listings-table>
  </transition>

我遇到的问题是有些用户点击浏览器后退按钮,期望最后一个组件加载。我想知道是否有一种方法可以基于后退按钮更改状态?

谢谢。


我认为这是你想要使用的 https://dev59.com/L3M_5IYBdhLWcg3wPAnU - Derek Pollard
1个回答

5

这是可行的。我和我的同事在制作此页面时也做了类似的事情。

为了使其工作,

  • url 是 listingFormActive 值真相的来源
  • 每次 listingFormActive 状态改变时,应将其状态存储在 url 中。
  • 应从 url 中检索 listingFormActive 的初始状态。

首先,请注意 listingFormActive。每当状态改变时,执行pushState以将其状态存储为URL查询参数。

watch: {
    listingFormActive: {
        handler(v) {
            history.pushState({
                listingFormActive: v
            }, null, `${window.location.pathname}?listingFormActive=${v}`);
        }
    }
}

添加一些获取URL查询参数的实用方法

methods: {
    currentUrlQuery() {
        return window.location.search
            .replace("?", "")
            .split("&")
            .filter(v => v)
            .map(s => {
                s = s.replace("+", "%20");
                s = s.split("=").map(s => decodeURIComponent(s));
                return {
                    name: s[0],
                    value: s[1]
                };
            });
    },
    getListingFormActive() {
        return this.currentUrlQuery().filter(obj => obj.name === 'listingFormActive').value;
    }
}
< p > listingFormActive 的初始状态应基于您在URL中保存的内容< /p >
data() {
    return {
        listingFormActive: this.getListingFormActive() == 'true' ? true : false
    }
},

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接