2

Vue开发问题汇总

 2 years ago
source link: https://lianpf.github.io/posts/%E5%BC%80%E5%8F%91%E6%97%A5%E8%AE%B0/vue%E5%BC%80%E5%8F%91%E9%97%AE%E9%A2%98%E6%B1%87%E6%80%BB/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Vue开发问题汇总…

一、Router

1.VueRouter 同一个/多个路由(复用同一个组件)页面不重新加载

问题描述:遇到相似的页面结构,我们通常通过以下两种方式加载同一个组件,达到组件实例复用的效果。毕竟,两个路由都渲染同个组件,比起销毁再创建,复用则显得更加高效。

  1. 一个路由添加不同的query、params等参数区分状态。

不过,复用组件实例意味着组件的生命周期钩子不会再被调用。那么会导致两种情况:

  1. 想对路由参数的变化作出响应的话,可以简单地 watch (监测变化) $route 对象
export default {
  mounted () {
    this.reload()
  },
  methods: {
    reload () {}
  },
  watch: {
    '$route' (to, from) {
      console.log('to=' + to)
      this.reload()
    }
  }
}
  1. 参数变更或者路由变化想要重新加载组件实例时,则需要 Layout内的router-view重新加载
    • router-view 增加key不过这种方式存在的弊端可以思考一下
    • v-if控制router-view,在根组件APP.vue中实现一个reload方法
<router-view :key="$route.fullPath"></router-view>

第二种:
Layout

<template class="dashboard-layout">
  <!-- Layout left-menu -->
  <left-menu></left-menu>
    
  <!-- Layout main -->
  <container>
    <router-view v-if="isRouterAlive" @collapseOrOpenMenu="collapseOrOpenMenu"></router-view>
    </container>
</template>
<script>

export default {
  name: 'AppLayout',
  components: {},
  data() {
    return {}
  },
  computed: {},
  methods: {
    async reload() {
      this.isRouterAlive = false
      // TODO:加载数据
      await this.getAppMenus()
      this.$nextTick(() => (this.isRouterAlive = true))
    }
  },
  async created() {
    // TODO:加载数据
    await this.getAppMenus()
    window.APP_PAGE_ROOT = this
  }
}
</script>

复用组件调用reload()

<template class="dashboard-page">
    // ... content
</template>
<script>

export default {
  name: 'ReusableComponent',
  components: {},
  data() {
    return {}
  },
  computed: {},
  watch: {
    $route: {
      deep: true,
      immediate: false,
      handler: function(to, from) {
        console.log('--page-preview-to--', to)
        if (to.path === '/dashboard/page' && to.query.pageId !== from.query.pageId) {
          if (!window.APP_PAGE_ROOT) return window.location.reload()
          window.APP_PAGE_ROOT.reload()
        }
      }
    }
  },
  methods: {}
}
</script>

最后, 希望大家早日实现:成为前端高手的伟大梦想!
欢迎交流~

微信公众号

本文版权归原作者曜灵所有!未经允许,严禁转载!对非法转载者, 原作者保留采用法律手段追究的权利!
若需转载,请联系微信公众号:连先生有猫病,可获取作者联系方式!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK