Home > Web Front-end > Vue.js > body text

A detailed summary of 25 Vue skills that you must use!

WBOY
Release: 2022-01-27 17:33:37
forward
2147 people have browsed it

This article brings you twenty-five tips when using Vue. There are many useful tips, some are very tricky, some are used almost every day, and some are more advanced - but they are all useful. I hope everyone has to help.

A detailed summary of 25 Vue skills that you must use!

# Learning to be a better Vue developer isn’t always about big concepts that take time and effort to master. Knowing a few tips and tricks can make your programming life easier – without a lot of repetitive work.

In the past few years of developing with Vue, I have learned many useful techniques. Some are tricky, some you use almost every day, and some are more advanced – but they all work.

1. Limit a prop to a list of types

Use the validator option in the prop definition to limit a prop type within a specific set of values.

export default {
  name: 'Image',
  props: {
    src: {
      type: String,
    },
    style: {
      type: String,
      validator: s => ['square', 'rounded'].includes(s)
    }
  }
};
Copy after login

This verification function accepts a prop and returns true or false if the prop is valid or invalid.

When simply passing in true or false to control certain conditions cannot meet the needs, I usually use this method.

Button type or warning type (info, success, danger, warning) are the most common usage. Color is also a great use.

2. Default content and extension points

Slots in Vue can have default content, which allows us to make components that are easier to use.

Copy after login

My favorite way to use default slots is to use them to create extension points.

We can take any part of the component, encapsulate it in a slot, and outside we can overwrite that part of the component with whatever we want. By default, it will still work the same way, but it will give you more options

Copy after login

Now we can use this component in many different ways. Simple, default way, or custom way.





  

    Do something a little different here   

Copy after login

3. Use quotes to listen to nested properties

You may not know this, we can easily listen to nested values ​​directly by using quotes:

watch {
  '$route.query.id'() {
    // ...
  }
}
Copy after login

4. Know when to use v-if (and when to avoid it)

Instead of using v-if , sometimes using v-show instead will have higher performance.

Copy after login

When v-if is opened or closed, it will create and completely destroy the element. Instead, v-show will create the element and leave it there, hiding it by setting its style to display: none.

If the component you want to switch has a high rendering cost, this will be more efficient.

On the other hand, if you don't need to execute the expensive component immediately, you can use v-if so that it will skip rendering it and make the page load faster. .

5. Shorthand for a single scoped slot (no template tag required)

Scopeed slots are very interesting, but in order to use them you must also use Many template tags.

Fortunately, there is a shorthand that lets us get away from it, but only if we use a single scope slot.

Normal writing:


  
Copy after login

Not used template:


  
Copy after login

Simple, straightforward, and amazing.

6. Conditionally rendering slots

Let's first look at how to do it, and then discuss why you want to hide the slot.

Every Vue component has a special $slots object that contains all your slots. The default slot key is default, and any named slot uses its name as the key.

const $slots = {
  default: ,
  icon: ,
  button: 
Copy after login

But this $slots object only applies to the slots of the component, not every defined slot.

Take this component that defines several slots, including several named slots.


Copy after login

If we only apply one slot to a component, then only that slot will show up in our $slots object.

Copy after login
$slots = { second:  }
Copy after login

We can use this in our components to detect which slots have been applied to the component, for example, by hiding the slot's wrapping element.

Copy after login

Now, the wrapper that applies the style p will only be rendered if we fill this slot with something.

If you don't use v-if, you will get an empty unnecessary p if there is no slot. Depending on the p style, this might mess up our layout and make the interface look weird.

So, why do we want to be able to render slots conditionally?

There are three main reasons to use conditional slots:

  • When using an encapsulated p to add a default style
  • The slot is Empty
  • If we combine default content with nested slots

For example, when we add a default style, we add a p# around the slot ##:

Copy after login
However, if the parent component does not apply content to that slot, we end up rendering an empty

p on the page.

  

This is a pretty great component, amirite?

  

       

  
Copy after login
The solution is to judge multiple conditions as mentioned above.

7. 如何监听一个插槽的变化

有时我们需要知道插槽内的内容何时发生了变化。


Copy after login

不幸的是,Vue没有内置的方法让我们检测这一点。

然而,我的朋友Austin想出了一个非常干净的方法,使用MutationObserver来做这件事。

MutationObserver接口提供了监视对DOM树所做更改的能力。它被设计为旧的Mutation Events功能的替代品,该功能是DOM3 Events规范的一部分。

export default {
  mounted() {
    // 当有变化时调用`update`
    const observer = new MutationObserver(this.update);

    // 监听此组件的变化
    observer.observe(this.$el, {
      childList: true,
      subtree: true
    });
  }
};
Copy after login

这个涉及的内容还是很多的,后面会单独出一篇文章来讲,记得关注刷碗智的公众号 哦

8. 将局部和全局的 style混合在一起

通常情况下,在处理样式时,我们希望它们能被划分到一个单独的组件中。

Copy after login

不过,如果需要的话,也可以添加一个非作用域样式块来添加全局样式



Copy after login

但要小心,全局样式是危险的,难以追踪。但有时,它们是一个完美的逃生舱口,正是你所需要的。

9. 重写子组件的样式–正确的方法

Scoped CSS在保持内容整洁方面非常棒,而且不会将样式引入应用的其他组件中。

但有时你需要覆盖一个子组件的样式,并跳出这个作用域。

Vue有一个 deep 选择器:

Copy after login

注意:如果你使用像SCSS这样的CSS预处理器,你可能需要使用/deep/来代替。

10. 用上下文感知组件创造魔法

**上下文感知组件(context-aware)**是“魔法的”,它们自动适应周围发生的事情,处理边缘情况、状态共享等等。

有3种主要的 context-aware ,但 Configuration 是我最感兴趣的一种。

1.状态共享

当你把一个大的组件分解成多个小的组件时,它们往往仍然需要共享状态。

我们可以在 "幕后 "做这些工作,而不是把这些工作推给使用者。

我们一般会把 Dropdown 组件分解成 SelectOption 组件,这样会获得更多的灵活性。但是为了方便使用,SelectOption组件彼此共享 selected 状态。





Copy after login

2. Configuration

有时,一个组件的行为需要根据应用程序的其他部分的情况来改变。这通常是为了自动处理边缘情况,否则处理起来会很烦人。

一个 PopupTooltip 应该重新定位,以便它不会溢出页面。但是,如果该组件是在一个modal 内,它应该重新定位,以便它不会溢出 modal。

如果Tooltip知道它是在一个模态里面,这可以自动完成。

3.样式

创建了 context-aware的CSS,根据父级或同级元素的情况应用不同的样式。

.statistic {
  color: black;
  font-size: 24px;
  font-weight: bold;
}

.statistic + .statistic {
  margin-left: 10px;
}
Copy after login

CSS变量让我们更进一步,允许我们在一个页面的不同部分设置不同的值。

11. 如何在Vue之外创建一个具有响应性的变量(Vue2和3)

如果你从Vue之外得到一个变量,让它具有反应性是很好的。

这样,我们就可以在computed propswatch和其他任何地方使用它,它的工作方式就像Vue中的任何其他状态一样。

如果我们使用的选项API,需要的只是将其放在组件的数据部分中:

const externalVariable = getValue();

export default {
  data() {
    return {
      reactiveVariable: externalVariable,
    };
  }
};
Copy after login

如果使用Vue3的组合API,可以直接使用refreactive

import { ref } from 'vue';

// 可以完全在Vue组件之外完成
const externalVariable = getValue();
const reactiveVariable = ref(externalVariable);

console.log(reactiveVariable.value);
Copy after login

使用 reactive 代替:

import { reactive } from 'vue';

//  可以完全在Vue组件之外完成
const externalVariable = getValue();
// reactive 只对对象和数组起作用
const anotherReactiveVariable = reactive(externalVariable);

// Access directly
console.log(anotherReactiveVariable);
Copy after login

如果你还在使用 Vue2,你可以使用observable而不是reactive来实现完全相同的结果。

12. v-for 中的解构

你知道可以在-vfor中使用解构吗?

Copy after login
Copy after login
Copy after login
Copy after login
  •   {{ name }}
  • 更广为人知的是,可以通过使用这样的元组从v-for中取出索引。

    Copy after login
    Copy after login
    Copy after login
    Copy after login
  •   {{ index + 1 }} - {{ movie }}
  • 当使用一个对象时,可以这样使用 key

    Copy after login
    Copy after login
    Copy after login
    Copy after login
  •   {{ key }}: {{ value }}
  • 也可以将这两种方法结合起来,获取key以及属性的 index

    Copy after login
    Copy after login
    Copy after login
    Copy after login
  •   #{{ index + 1 }}. {{ key }}: {{ value }}
  • 13. 在指定范围内循环

    v-for指令允许我们遍历数组,但它也允许我们遍历一个范围

    Copy after login

    渲染结果:

    Item #1
    Item #2
    Item #3
    Item #4
    Item #5
    Copy after login

    当我们使用带范围的v-for时,它将从1开始,以我们指定的数字结束。

    14. 监听你的组件中的任何东西

    export default {
      computed: {
        someComputedProperty() {
          // Update the computed prop
        },
      },
      watch: {
        someComputedProperty() {
          // Do something when the computed prop is updated
        }
      }
    };
    Copy after login

    我们可以监听:

    • 计算属性
    • props
    • 嵌套值

    如果你使用组合API,任何值都可以被监视,只要它是一个refreactive对象。

    15.窃取 prop 类型

    我从一个子组件中复制 prop 类型,只是为了在一个父组件中使用它们。但我发现,偷取这些 prop 类型要比仅仅复制它们好得多。

    例如,我们在这个组件中使用了一个Icon组件。

    Copy after login

    为了让它工作,我们需要添加正确的 prop 类型,从``Icon`组件复制。

    import Icon from './Icon';
    export default {
      components: { Icon },
      props: {
        iconType: {
          type: String,
          required: true,
        },
        iconSize: {
          type: String,
          default: 'medium',
          validator: size => [
            'small',
            'medium',
            'large',
            'x-large'
          ].includes(size),
        },
        iconColour: {
          type: String,
          default: 'black',
        },
        heading: {
          type: String,
          required: true,
        },
      },
    };
    Copy after login

    多么痛苦啊。

    Icon 组件的 prop类型被更新时,我们肯定会忘记返回这个组件并更新它们。随着时间的推移,当该组件的 prop类型开始偏离Icon组件中的 prop 类型时,就会引入错误。

    因此,这就是为什么我们要窃取组件的 prop 类型:

    import Icon from './Icon';
    export default {
      components: { Icon },
      props: {
        ...Icon.props,
        heading: {
          type: String,
          required: true,
        },
      },
    };
    Copy after login

    不需要再复杂了。

    除了在我们的例子中,我们把 icon 加在每个 prop 名称的开头。所以我们必须做一些额外的工作来实现这一点。

    import Icon from './Icon';
    
    const iconProps = {};
    
    Object.entries(Icon.props).forEach((key, val) => {
      iconProps[`icon${key.toUpperCase()}`] = val;
    });
    
    export default {
      components: { Icon },
      props: {
        ...iconProps,
        heading: {
          type: String,
          required: true,
        },
      },
    };
    Copy after login

    现在,如果Icon组件中的 prop 类型被修改,我们的组件将保持最新状态。

    但是,如果一个 prop 类型从 Icon 组件中被添加或删除了呢?为了应对这些情况,我们可以使用v-bind和一个计算的 prop 来保持动态。

    16. 检测元素外部(或内部)的单击

    有时我需要检测一个点击是发生在一个特定元素el的内部还是外部。这就是我通常使用的方法。

    window.addEventListener('mousedown', e => {
      // 获取被点击的元素
      const clickedEl = e.target;
      
      if (el.contains(clickedEl)) {
       //在 "el "里面点击了
      } else {
       //在 "el "外点击了
      }
    });
    Copy after login

    17. 递归插槽

    有一次,我决定看看我是否可以只用模板来做一个v-for组件。在这个过程中,我也发现了如何递归地使用槽。

    
    
    Copy after login

    如果你想用作用域插槽来做这件事,只是需要一些调整

    Copy after login

    下面是这个组件的使用方法。

    Copy after login

    18. 组件元数据

    并不是添加到一个组件的每一点信息都是状态。有时我们需要添加一些元数据,给其他组件提供更多信息。

    例如,如果正在为谷歌 analytics这样的分析仪表:

    A detailed summary of 25 Vue skills that you must use!

    如果你想让布局知道每个小组件应该占多少列,你可以直接在组件上添加元数据。

    export default {
      name: 'LiveUsersWidget',
      //  只需将其作为一个额外的属性添加
      columns: 3,
      props: {
        // ...
      },
      data() {
        return {
          //...
        };
      },
    };
    Copy after login
    export default {
      name: 'LiveUsersWidget',
      //   只需将其作为一个额外的属性添加
      columns: 3,
      props: {
        // ...
      },
      data() {
        return {
          //...
        };
      },
    };
    Copy after login

    你会发现这个元数据是组件上的一个属性。

    import LiveUsersWidget from './LiveUsersWidget.vue';
    const { columns } = LiveUsersWidget;
    Copy after login

    我们也可以通过特殊的$options属性从组件内部访问元数据。

    export default {
      name: 'LiveUsersWidget',
      columns: 3,
      created() {
        //  `$options` contains all the metadata for a component
        console.log(`Using ${this.$options.metadata} columns`);
      },
    };
    Copy after login

    只要记住,这个元数据对组件的每个实例都是一样的,而且不是响应式的。

    这方面的其他用途包括(但不限于):

    • 保持单个组件的版本号
    • 用于构建工具的自定义标志,以区别对待组件
    • 在计算属性、数据、watch 等之外为组件添加自定义功能
    • 其它

    19. 多文件单文件组件

    这是**SFC(单文件组件)**的一点已知功能。

    可以像常规HTML文件一样导入文件:

    
    
    
    Copy after login

    如果你需要分享样式、文件或其他任何东西,这可能会非常方便。

    20. 可重复使用的组件并不是你所想的那样

    可重复使用的组件不一定是大的或复杂的东西。

    我经常让小的和短的组件可以重复使用。

    因为我没有到处重写这段代码,所以更新它变得更加容易,而且我可以确保每个OverflowMenu的外观和工作方式都完全一样–因为它们是一样的!"。

    
    
    Copy after login

    在这里,我们采用了一个菜单组件,但在触发它的按钮上添加了一个 ellipsis 图标。(省略号)的图标来触发它的打开。

    这似乎不值得把它做成一个可重复使用的组件,因为它只有几行。难道我们就不能在每次要使用这样的菜单时添加图标吗?

    但是这个OverflowMenu将被使用几十次,现在如果我们想更新图标或它的行为,我们可以非常容易地做到。而且,使用它也更简单了。

    21. 从组件外部调用一个方法

    我们可以从一个组件的外部通过给它一个 ref 用来调用一个方法。

    
    
    Copy after login
    Copy after login
    // Somewhere in Parent.vue
    this.$refs.child.method();
    Copy after login
    Copy after login

    再解释一下这个问题。

    有时候,“最佳实践”并不适用于你正在做的事情,你需要一个像这样的逃生口。

    通常情况下,我们使用 props 和 events 在组件之间进行交流。props 被下发到子组件中,而events 被上发到父组件中。

    Copy after login
    // Child.vue
    export default {
      props: ['trigger'],
      watch: {
        shouldCallMethod(newVal) {
          if (newVal) {
            // Call the method when the trigger is set to `true`
            this.method();
          }
        }
      }
    }
    Copy after login

    这可以正常工作,但只能在第一次调用时使用。如果您需要多次触发此操作,则必须进行清理并重置状态。逻辑是这样的

    • 父组件将 true 传递给触发器 prop
    • Watch 被触发,然后 Child 组件调用该方法
    • 子组件发出一个事件,告诉父组件该方法已被成功触发
    • Parent组件将 trigger 重置为 false,所以我们可以从头再来一次

    相反,如果我们在子组件上设置一个 ref,我们可以直接调用该方法:

    
    
    Copy after login
    Copy after login
    // Somewhere in Parent.vue
    this.$refs.child.method();
    Copy after login
    Copy after login

    是的,我们打破了 “props down, events up"” 的规则,我们打破了封装,但是这样做更清晰,更容易理解,所以是值得的

    有时,"最好的 "解决方案最终会成为最糟糕的解决方案。

    22. 监听数组和对象

    使用 watcher 最棘手的部分是,有时它似乎不能正确触发。

    通常,这是因为我们试图监听数组或对象,但没有将deep设置为true

    export default {
      name: 'ColourChange',
      props: {
        colours: {
          type: Array,
          required: true,
        },
      },
      watch: {
        // 使用对象语法,而不仅仅是方法
        colours: {
          // 这将让Vue知道要在数组内部寻找
          deep: true,
    
          handler()
            console.log('The list of colours has changed!');
          }
        }
      }
    }
    Copy after login

    使用Vue 3的API会是这样的:

    watch(
      colours,
      () => {
        console.log('The list of colours has changed!');
      },
      {
        deep: true,
      }
    );
    Copy after login

    23. 用Vue Router进行深度链接

    我们可以在URL中存储(一点)状态,允许我们直接跳到页面上的一个特定状态。

    例如,你加载一个已经选择了日期范围过滤器的页面:

    someurl.com/edit?date-range=last-week
    Copy after login

    这对于应用中用户可能共享大量链接的部分来说是非常棒的,对于服务器渲染的应用,或者在两个独立的应用之间通信的信息比普通链接通常提供的更多。

    我们可以存储过滤器、搜索值、模态框是打开还是关闭,或者在列表的哪个位置滚动以完美地实现无限分页。

    使用 vue-router 获取查询参数是这样工作的(这也适用于大多数Vue框架,如Nuxt和Vuepress):

    const dateRange = this.$route.query.dateRange;
    Copy after login

    为了改变它,我们使用 RouterLink 组件并更新 query

    Copy after login

    24. template 标签的另一个用途

    template 标签可以在模板中的任何地方使用,以更好地组织代码。

    我喜欢用它来简化v-if逻辑,有时也用v-for

    在这个例子中,我们有几个元素都使用同一个v-if条件。

    Copy after login

    这有点笨拙,而且一开始并不明显,一堆这样的元素被显示和隐藏在一起。在一个更大、更复杂的组件上,这可能是一个更糟糕的情况

    但我们能优化它。

    我们可以使用 template 标签来分组这些元素,并将 v-if 提升到模板 template 本身。

    Copy after login

    现在看起来就更容易理解,而且它在做什么,一目了然。

    25. 处理错误(和警告)的更好方法

    我们可以为Vue中的错误和警告提供一个自定义处理程序。

    // Vue 3
    const app = createApp(App);
    app.config.errorHandler = (err) => {
      alert(err);
    };
    
    // Vue 2
    Vue.config.errorHandler = (err) => {
      alert(err);
    };
    Copy after login

    像 Bugsnag 和 Rollbar 这样的错误跟踪服务,可以钩住这些处理程序来记录错误,但你也可以用它们来更优雅地处理错误,以获得更好的用户体验。

    例如,如果一个错误未被处理,应用程序不会直接崩溃,你可以显示一个完整的错误屏幕,让用户刷新或尝试其他东西。

    在 Vue3 中,错误处理程序只能处理 templatewatcher 错误,但是 Vue2的错误处理程序可以捕获几乎所有错误。这两个版本中的警告处理程序只在开发阶段有效。

    代码部署后可能存在的BUG没法实时知道,事后为了解决这些BUG,花了大量的时间进行log 调试,这边顺便给大家推荐一个好用的BUG监控工具 Fundebug。

    【相关推荐:《vue.js教程》】

    The above is the detailed content of A detailed summary of 25 Vue skills that you must use!. For more information, please follow other related articles on the PHP Chinese website!

    Related labels:
    vue
    source:csdn.net
    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
    Popular Tutorials
    More>
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!