理理Vue细节(推荐)

2020-06-13 10:33:58易采站长站整理

<option value="abc">ABC</option>
</select>

修饰符.lazy:在change时而非input时更新 <input v-model.lazy=”msg” >

注:change事件是在input失去焦点时触发,即用于单选、多选框和选择框,而input事件是在value值变化时触发,但脚本改变value值时不会触发,即用于text和textarea

修饰符.number:输入值转为数值

修饰符.trim:过滤收尾空白字符

12. Prop

使用v-bind=”obj”会将对象的每个属性都作为一个独立的prop传入进去,所以接受时也需要逐个属性接收。


<test v-bind="obj"></test>

props虽然是单向数据流,但对于引用类型,子组件还是可以改变父组件的状态。

props会在组件实例创建之前进行验证,所以实例的属性再default或validator中是不可用的。

13. 自定义事件

自定义事件需要注意事件名为小写或-分隔,因为$emit(‘BaseEvent’)虽然事件名不会变,但在html中该事件名会被转化为小写,不会监听到。

14. slot

具名插槽


<base-layout>
<template v-slot:header>
<h1>Here might be a page title</h1>
</template>
<!-- 默认插槽也可不用加上template和v-slot -->
<template v-slot:default>
<p>A paragraph for the main content.</p>
<p>And another one.</p>
</template>
<template v-slot:footer>
<p>Here's some contact info</p>
</template>
</base-layout>

作用域插槽


<!-- current-user组件 -->
<span>
<slot :user="user">
{{ user.lastName }}
</slot>
</span>

<!-- 父级组件通过自定义名称访问子级作用域 -->
<current-user>
<template v-slot:default="slotProps">
{{ slotProps.user.firstName }}
</template>
</current-user>

<!-- 支持缩写和解构 -->
<current-user>
<template #default="{ user = { firstName: Gust } }">
{{ user.firstName }}
</template>
</current-user>

15. 组件通信

vuex/eventBus
prop/$emit
$children/$parent
provide/inject
$refs


// 父或祖先级
provide: function () {
return {
getMap: this.getMap
}
}

// 后代级
inject: ['getMap']

 16. scope

scoped 属性会自动添加一个唯一的属性 (比如 data-v-21e5b78) 为组件内 CSS 指定作用域,编译的时候 .list-container:hover 会被编译成类似 .list-container[data-v-21e5b78]:hover