在 Vue.js 2 中,ref、props 和 mixin 是常用的概念和特性,它们为我们构建可维护、可扩展的 Vue 应用提供了便利。本文将深入介绍这些概念的含义、用法和作用。
1. ref
在 Vue 中,ref 是一个特殊的属性,用于在模板或组件实例中引用 DOM 元素或子组件。通过 ref,我们可以直接访问到对应的 DOM 元素或子组件实例,从而进行操作或者获取信息。
使用方式:
<template>
<div ref="myDiv">Hello, Vue!</div>
</template>
<script>
export default {
mounted() {
console.log(this.$refs.myDiv); // 输出对应的 DOM 元素
}
}
</script>
2. props
props 是 Vue 中用于父子组件通信的机制。通过在子组件中定义 props,可以接收来自父组件的数据传递。在父组件中,通过绑定属性的方式将数据传递给子组件。
三种 props 的写法:
1.字符串数组:
props: ['message', 'count']
2.对象形式:
props: {
message: String,
count: {
type: Number,
default: 0
}
}
3.使用函数校验:
props: {
message: {
type: String,
required: true,
validator: function (value) {
return value.length <= 10;
}
}
}
3. mixin
mixin 是 Vue 中用于代码复用的一种机制。它允许我们在多个组件之间共享代码,提高了代码的复用性和可维护性。通过 mixin,我们可以将一些通用的逻辑、方法或者生命周期钩子提取出来,然后在多个组件中引用。
两种混入方式:
1.全局混入:通过 Vue.mixin 全局注册 mixin,会影响到每个 Vue 实例。
2.局部混入:在组件内部通过 mixins 选项引入 mixin,只会影响到当前组件。
// 全局混入
Vue.mixin({
created() {
console.log('Global mixin created');
}
});
// 局部混入
export default {
mixins: [myMixin]
}
通过全局混入和局部混入,我们可以灵活地在 Vue 应用中使用 mixin,实现代码的复用和功能的扩展。
- 打卡4.14