美文网首页
解决vue路由跳转页面不刷新(页面变量加载不自动刷新)问题的两种

解决vue路由跳转页面不刷新(页面变量加载不自动刷新)问题的两种

作者: zoomlaCMS | 来源:发表于2020-02-20 19:12 被阅读0次

    路由参数改变,页面数据不更新解决方法:

    http://localhost:8080/#test?id=1

    http://localhost:8080/#test?id=2,参数切换后,数据未更新

    vue-router同路由$router.push不跳转一个简单解决方案

    vue-router跳转一般是这么写:

    toCurrentPage: function(thisId){
              this.$router.push({path:'/test ', query: { id: thisId, option: ""}});
     }
    

    但是当遇到,需要跳转同页面不同query的情况,上面的方法不起作用。当然了,从性能来说,理论上这种情况最佳的解决方案,是把需要刷新的包裹成一个init function,跳转的方法,传参再次调用init方法。balabalabala……不在赘述。

    但是另一些情况,基本页面所有组件都需要刷新,再次加载对开销影响不大,需要history.back以保证操作逻辑顺畅……我们只要跳转加载如此而已,那么其实也很简单,只需在上述方法基础上加上:

    watch: {
        '$route' (to, from) {
            this.$router.go(0);
        }
    },
    

    下面是实际使用有效方法二则:

    方法一

    通过路由传参跳转界面,页面没有刷新

    解决方法:在 router-view 中加 :key="$route.fullPath"

    <router-view :key="$route.fullPath"></router-view>
    

    方法二

    再跳转后的路由观察路由变化,进行页面刷新(这种方法相对来说会加载慢一些,用户体验差)。

            watch: {    
            '$route' (to, from) {   
                 this.$router.go(0);
                 }
            }
    

    附一个完整页面示例:

    <template>
    <div>
        <div class="container">
        <ul class="list-unstyled">
        <li  v-for="item in list" :key="item.GeneralID"><a href="javascript:;" @click="navTo(item)">{{item.Title}}</a></li>
        </ul>
        </div>
    </div>
    </template>
    <script>
        export default {
            data: function() {
                var model = {
                    list: []
                };
                var nid = this.$route.params.nid;
                this.jsp("content_list", {"nid": nid}).then((ret) => {
                    model.list = JSON.parse(ret.result);
                });
                return model;
            },
            methods: {
                navTo:function(item){this.$router.push("/Content/"+item.GeneralID);}
            },
            watch: {    
            '$route' (to, from) {   
                 this.$router.go(0);
                 }
            }
        }
    </script>
    

    相关文章

      网友评论

          本文标题:解决vue路由跳转页面不刷新(页面变量加载不自动刷新)问题的两种

          本文链接:https://www.haomeiwen.com/subject/rqhfqhtx.html