vue2升级vue3:composition api中监听路由参数改变

开发者 2024-9-12 18:52:42 44 0 来自 中国
vue2 的watch回顾
我们先回顾一下vue2中watch
《watch性能优化:vue watch对象键值分析-immediate属性详解》
《vue中methods/watch/computed对比分析,watch及computed原理发掘》
watch和computed很相似,watch用于观察和监听页面上的vue实例,固然在大部分环境下我们都会利用computed,但如果要在数据厘革的同时举行异步利用大概是比力大的开销,那么watch为最佳选择。watch为一个对象,键是必要观察的表达式,值是对应回调函数。值也可以是方法名,大概包罗选项的对象。
如果在data中没有相应的属性的话,是不能watch的,这点和computed不一样。
实用场景:






watch实现原理
this.$watch()手动注入
比如我们可以手动注入监听器,只有一定条件时,才必要监听,这个也可以大大的提升性能
created() {
  this.debounceEvent = debounce(
    this.demoEvent,
    this.curretnDelay,
  );
  // 只有图表编辑页面,才必要监听
  if (this.$route.name === 'chartDialog') {
    this.$watch('dataOptions', {
      handler() {
        // 只有图表编辑页面,才必要监听
        this.renderData(true);
        console.log('watch dataOptions');
      },
      deep: true,
    });
  }
}
vue2 的watch不再赘述
vue3 composition api 监听路由厘革
https://router.vuejs.org/guide/advanced/composition-api.html#accessing-the-router-and-current-route-inside-setup
https://router.vuejs.org/zh/api/#routelocationraw
https://router.vuejs.org/zh/guide/essentials/dynamic-matching.html# 相应路由参数的厘革
组件内路由导航保卫
利用组件内路由导航保卫 onBeforeRouteUpdate
setup(){
   onBeforeRouteUpdate( to =>{
   // console.log(to.params, to.query)
   })
}
保举利用这个方法
导航保卫-全局后置钩子
路由保卫中监听路由参数,再利用盘算属性导出,可全局利用
import { RouteParams, LocationQueryRaw } from 'vue-router';
import { computed, reactive } from 'vue';
import router from '@/router/index';
const routeData = reactive<{params: RouteParams, query: LocationQueryRaw}>({ params: {}, query: {} });
router.afterEach((route) => {
  routeData.params = route.params;
  routeData.query = route.query;
});
export  function useRouteParam() {
  return computed(() => routeData.params);
}
export function useRouteQuery() {
  return computed(() => routeData.query);
}
在页面内利用
export default defineComponent({
 setup() {
   const params = useRouteParam();
   const spaceId = params.value.space_uid;
 }
}
z'归并时不保举的。没有须要全局
将参数与路由解耦,注入到组件的props中去举行监听
// router/index.js
const router = new VueRouter({
    routes: [{
        path: 'article/:articleId'
        component: Article,
        //props: (route) => {articleId: route.params.articleId} //原文返回对象没加小括号包裹,具有二义性
        props: (route) => ({articleId: route.params.articleId})
    }]
})
// your component
setup(props) {
   const article = reactive({...});
   function fetchArticle(id) {
      //assign article..
   }
   watch(() => props.articleId, fetchArticle)
   return { article };
}
必要立刻实行回调函数,可以引入watchEffect
必要立刻实行回调函数,可以引入watchEffect,不必要传参数直接把回调扔进去,代码简介明确(回调中自动网络依靠,不要要手动指定,且第一次回调立刻触发)
import { watchEffect } from "vue"
// ···
setup(props){
   function initData(){
     // 利用了props
  }
  watchEffect(initData)  //initData立刻实行,且当props中依靠的数据改变时,会自动实行
}
在组件内watch
setup() {
   const article = reactive({...});
   function fetchArticle(id) {
      //assign article..
   }
   const route = useRoute();
   watch(
      () => route.params,
      () => {
        const { articleId } = route.params;
        if (articleId) {
          fetchArticle(articleId);
        }
      },
      { immediate: true, deep: true }
    );
}
官方文档给的案例也是这个:https://router.vuejs.org/guide/advanced/composition-api.html#accessing-the-router-and-current-route-inside-setup
页面跳转传了 params 但是无效
传 params 的时间要传 name
加入 { immediate: true, deep: true } 就可以了
参考文章:
Vue3 监听路由厘革 https://trycoding.fun/JavaScript/vue3-watch-route/
Vue3.0 中监听路由参数的改变方法大全 https://blog.csdn.net/qq_41777791/article/details/113100730
https://medium.com/js-dojo/watch-vue-route-params-query-with-composition-api-97b3c8c402e
转载本站文章《vue2升级vue3:composition api中监听路由参数改变》,
请注明出处:https://www.zhoulujun.cn/html/webfront/ECMAScript/vue3/8860.html
您需要登录后才可以回帖 登录 | 立即注册

Powered by CangBaoKu v1.0 小黑屋藏宝库It社区( 冀ICP备14008649号 )

GMT+8, 2024-10-18 19:22, Processed in 0.128204 second(s), 32 queries.© 2003-2025 cbk Team.

快速回复 返回顶部 返回列表