一、组件自定义v-model
一个组件上的 v-model默认会利用名为 value的 prop 和名为 input的事件,来双向绑定。当然名称也可以自定义。如下:
//绑定text1的prop值,发布事件change1的名称
model: {
prop: 'text1',
event: 'change1'
},
通过.sync修饰符,也可以控制父组件的值
this.$emit('update:title', newTitle)
<children :title.sync></children>
二、$nextTick
由于vue是异步渲染的,所以在修改vue的data等数据之后,等所有函数执行完才会进行dom渲染。我们需要获取渲染后的dom就需要使用$nextTick。
三、动态组件、函数式组件、异步组件
-
使用component组件来动态加载需要组件。
<component :is="name"></component> //修改name对应组件名称,就会加载该组件。组件必须全局注册或者局部注册过 -
函数组件写法:
<template functional> <div> <p v-for="(item,index) in props.items" :key="index" @click="props.itemClick(item)" /> </div> </template> -
异步组件
components: { 'my-component': () => import('./my-async-component') } //也可以增加状态 components: { 'my-component': () => ({ // 需要加载的组件 (应该是一个 `Promise` 对象) component: import('./MyComponent.vue'), // 异步组件加载时使用的组件 loading: LoadingComponent, // 加载失败时使用的组件 error: ErrorComponent, // 展示加载时组件的延时时间。默认值是 200 (毫秒) delay: 200, // 如果提供了超时时间且组件加载也超时了, // 则使用加载失败时使用的组件。默认值是:`Infinity` timeout: 3000 }) }
四、keep-alive,缓存组件
使用keep-alive组件可以缓存已经加载的组件。使用在动态组件、路由组件、v-if组件上。
- 缓存组件,是vue内置的一个组件,可以使被包含的组件保留状态,避免重新渲染
- 一般结合路由和动态组件一起使用,用于缓存组件;
- 提供了include和exclude,两者都支持字符串和正则表达式,include表示只有名称匹配的组件会被缓存,exclude表示任何名称匹配的组件都不会被缓存,其中exclude的优先级比include高。
五、混入mixin
主要用来提取组件中共同的属性,方法。
//mixin文件
export const toggle ={
data(){
return {
isShowing:false
}
},
methods:{
toggleShow(){
this.showing =!this,isShowing;
}
}
}
//组件中使用
import {toggle} './mixins/toggle'
export default{
name:'model',
mixins:[toggle],
}
六、监听子组件生命周期
// Parent.vue
<Child @hook:mounted="doSth" />
methods:{
doSth(){
//some codes here
}
}
hook还可以监听当前组件的生命周期
七、访问组件
- 访问根组件使用
this.$root,可以做发布消息和订阅 - 父组件访问子组件
<base-input ref="usernameInput"></base-input>给取件赋予ID应用,在通过this.$refs.usernameInput访问子组件。 - 跨组件访问,通过依赖注入的方式。
//祖组件,返回对象
provide: function () {
return {
getMap: this.getMap
}
}
//孙组件注入key
inject: ['getMap']