Vue实用解决方案

1、Vue scoped CSS 与深度作用选择器 /deep/

With scoped, the parent component's styles will not leak into child components. However, a child component's root node will be affected by both the parent's scoped CSS and the child's scoped CSS. This is by design so that the parent can style the child root element for layout purposes

大概意思:使用scoped作用域,父组件的样式不会渗透到子组件中。但是,子组件的根节点将受到父作用域的CSS和子作用域的CSS的影响。这是通过设计使父节点可以为布局目的而调整子根元素的样式。

那么我们就会遇到一个坑爹的问题:当我们使用v-html标签时,我们期望v-html出来的内容的样式在父组件中编写。例如:期望i标签中的数据颜色为红色,然并卵,无效,欲哭无泪啊 。

<template>
  <div id="app">
    <div v-html=""></div>
  </div>
</template>

<script>
export default {
  name: 'App',
  data() {
    return {
      content_html: '公司当前干部平均年龄<i>40.89</i>岁,年龄低于35岁的干部占比<i>5.00%</i>,30-40的干部占比<i>17.50%</i>,40-50的干部占比<i>34%</i>,45-50的干部占比<i>36.50%</i>,50岁以上的干部占比<i>7%</i>。',
    };
  }
};
</script>

<style scoped>
#app {
  i {
    color:red;
    font-style:normal;
  }
}
</style>

查阅文档后scoped-css,发现有一种解决方案:深度选择器 /deep/。

修改后为(样式部分):

<style lang="less" scoped>
#app {
  /deep/ i {
    color:red;
    font-style:normal;
  }
}
</style>

 有的帖子中会推荐使用 >>>,其本质都是一样的,然而三箭头的写法存在一些兼容性。在一些预编译语言中,例如sass,它无法正确的解析三箭头,所以呢,还是推荐使用  /deep/

2、Vue 获取路由参数变化

当组件被设置为常驻内存(keep-alive),会极大提高组件切换的性能,每次加载都不需要重新执行一遍生命周期。但是问题也来了,如何保证数据的重新渲染呢?对于路由传参,似乎也被忽视了 。经测试,Vue 普通组件也存在这个问题,这是 Vue 的 diff 机制导致的,为了性能最优化,不会执行多余的渲染操作。

在vue-router中推荐了2中暴力的方式:

1、复用组件时,想对路由参数的变化作出响应的话,你可以简单地 watch (监测变化) $route 对象:

const User = {
  template: '...',
  watch: {
    '$route' (to, from) {
      // 对路由变化作出响应...
    }
  }
}

2、或者使用 2.2 中引入的 beforeRouteUpdate 导航守卫

扫描二维码关注公众号,回复: 5883554 查看本文章
const User = {
  template: '...',
  beforeRouteUpdate (to, from, next) {
    // react to route changes...
    // don't forget to call next()
  }
}

3、这里推荐一种更优雅的方案:在最新版本的 vue-router 中,官方推荐使用 props 将组件和路由解耦,这样可以从 props 中获得参数,而不需要监控 $router 对象,案例如下:

const User = {
  props: ['id'],
  template: '<div>User {{ id }}</div>'
}
const router = new VueRouter({
  routes: [
    { path: '/user/:id', component: User, props: true },

    // 对于包含命名视图的路由,你必须分别为每个命名视图添加 `props` 选项:
    {
      path: '/user/:id',
      components: { default: User, sidebar: Sidebar },
      props: { default: true, sidebar: false }
    }
  ]
})

 

 以上是做vue项目遇到的两个比较经典的实用技巧和解决方案,大家可以参考一下哦,希望对你有所帮助。欢迎关注同步微信公众号:前端小菜的进阶之路

公众号:Mr-Small_Teem

猜你喜欢

转载自blog.csdn.net/jingsi1991/article/details/83514857