这里我收集了一些vue面试问到的知识点,通过查看网站上对应的内容,对这些内容归纳总结:
1.vue中的指令:
2.指令v-model的原理:
<input v-model="price">
本质上等于:
<input type="text" :value="price" @input="price=$event.target.value">
通过input标签的input事件进行绑定,使用的是v-bind指令和input语法糖实现数据更新
在组件上使用v-model时:
父组件:
<template>
<child v-model="name"></child>
</template>
子组件:
<template>
<input v-model="name" @input="$emit('input',$event.target.value)"/>
</template>
export default {
props:{
value:String
},
data(){
return {}
}
但是对于checkbox,radio这些标签使用input事件就不太适合了,这时候就必须使用新的触发事件,vue提供了model来绑定新的事件
父组件:
<template>
<child v-model="checked"></child>
</template>
子组件:
<template>
<input type="checkbox" v-model="checked" @change="$emit('change',$event.target.checked)"/>
</template>
export default {
model:{
prop:'checked', //绑定prop中的数据
event:'change' //绑定事件
},
props:{
checked:Boolen
},
data(){
return {}
}
3.自定义指令
// 注册一个全局自定义指令 `v-focus`
Vue.directive('focus', {
inserted: function (el) { // 当被绑定的元素插入到 DOM中时……
// 聚焦元素
el.focus()
} })
如果想注册局部指令,组件中也接受一个 directives 的选项:
directives: {
focus: {
// 指令的定义
inserted: function (el) {
el.focus()
}
}
}
然后你可以在模板中任何元素上使用新的 v-focus property,如下:
<input v-focus>
一个指令定义对象可以提供如下几个钩子函数 (均为可选):
。