为什么不建议使用全局组件(html文件)/单文件组件(vue组件)的好处
1.全局定义强制要求每个component中的命名不得重复
2.字符串模板缺乏语法高亮,在HTML有多行的时候需要用到 ‘’,不美观
3.不支持CSS
4.没有构建步骤,只能使用HTML和ES5语法,不能使用CSS
如果使用单文件组件(文件拓展名为.vue),上述问题都能解决,并且可以使用webpack等构建工具
— Vue官方文档
什么是MVVM
在vue中如果更新数据,页面会自动刷新;
页面中的数据如果更新,data中的数据也会有相应的变化
M:model --数据(实例中的data)
V:view --视图/页面/模板(template)
VM:view-model --vue实例(通过VM来实现数据和模板的关联)(let vue = new Vue() / export default)
组件名大小写规范
定义组件名可使用
1.kebab-case (使用-来连接小写的单词)
Vue.component('component-name',{/*...*/})
引用自定义元素时
<component-name>
2.使用PascalCase(大驼峰写法)
Vue.component('ComponentName',{/*...*/})
当使用PascalCase定义一个组件时,引用时kebab-case写法和PascalCase写法都可以使用
<ComponentName>
<component-name>
但是如果是直接在DOM(非字符串模板)中使用,只有kebab-case有效
v-on的非常用用法
修饰符: --加在绑定事件后
.stop - 调用 event.stopPropagation()。
.prevent - 调用 event.preventDefault(),阻止默认事件行为,例如a链接跳转。
例如
<a href="http://www.abcd.com" @click.prevent="noJump" />
.capture - 添加事件侦听器时使用 capture 模式。
.self - 只当事件是从侦听器绑定的元素本身触发时才触发回调。
.{keyCode | keyAlias} - 只当事件是从特定键触发时才触发回调。
例如
<input type="text" @keyup.enter="eventName" />
.native - 监听组件根元素的原生事件。
.once - 只触发一次回调。
.left - (2.2.0) 只当点击鼠标左键时触发。
.right - (2.2.0) 只当点击鼠标右键时触发。
.middle - (2.2.0) 只当点击鼠标中键时触发。
.passive - (2.3.0) 以 { passive: true } 模式添加侦听器
如果事件没有传参,会有默认的事件参数,实参为vue/组件实例
//template
<input type="button" @click="add" />
//script
methods:{
add(e){
console.log(e)
//MouseEvent {isTrusted: true, screenX: 928, screenY: 133, …}
}
}
如果事件有设形参,又想拿到事件参数,需要在事件后手动传递$event
//template
<input type="button" @click="add("OK",$event)" />
//script
methods:{
add(msg,e){
console.log(msg)
//"OK"
console.log(e)
//MouseEvent {isTrusted: true, screenX: 928, screenY: 133, …}
}
}
Vue的VM中this的指向
1.如果不使用箭头函数,即在函数体内,this是指向整个Vue/组件实例
官方原话大意为:
在Vue所有的生命周期钩子方法(如created,mounted, updated以及destroyed)里使用this,this指向调用它的Vue实例,即(new Vue)
2.如果使用箭头函数 ,箭头函数本身没有this,箭头函数中的this是继承的,所以由上下文决定.
(默认指向在定义它时所处的对象(宿主对象),而不是执行时的对象,)