vue经验总结

1. vue中获取dom节点时机

vue组件中获取dom节点一定要在mounted周期之后的下一次事件循环,包括 component.$refs,component.$el,component.$children等
一般写法在nextTick中获取,mounted不是必须:
mounted(){
  this.$nextTick(() = {
    const el = this.$el;
  })
}

2.watch变量合并更新

vue的dom更新是异步的,因此watch一个变量时候,短时间内频繁更新该变量的值,其watch方法只会执行一次
例如,在for循环总更新一个被watch的变量。解决方法,可以使用setTimeout延迟更新或者直接调用watch的方法。

3.vuex的页面弹出error

可以在vuex的module state中添加error字段,ajax出错时,将错误赋值为error,
组件内再watch error字段,弹出error内容

4.watch $route触发时机

watch $route的方法只在组件被复用,即同一个组件内的路由切换时候,即同一个一级路由下的二级路由发送变化时候触发。
如果是一级路由发生变化,组件会被重新创建,会触发created方法,不会触发$route。在二级路由之间跳转,只有一级路由相同才触发。
例如:

/user/:id, id是个参数 /user/1 到 /user/2 会触发user组件的$route方法
/account,/account/list,/account/create 从/account/list到/account/create会触发account组件的$route方法,从/account/list到/user/1不会触发

const User = {
  template: '...',
  watch: {
    '$route' (to, from) {
      
    }
  }
}

5. Unknown custom element: <router-view>

未引入vueRouter
import vueRouter from 'vue-router'
Vue.use(vueRouter)

6. vue的props在模板中不能用驼峰 

在vue的props中可以使用驼峰写法的属性,但是在模板中必须改成中划线形式,例如backClass在模板中必须改成back-class,否则会被当成是html标签的自定义属性,在props中取不到值

7. vue获取路由参数

在vue组件中,使用this.$route获取路由相关信息,不是$router.

//params

this.$route.params

//query

this.$route.query

原文地址:https://www.cnblogs.com/mengff/p/6849693.html