鉴于官方文档案例不够齐全,结合文档笔者总结了一下相对齐全的案例并均可运行出结果。可以更加深入具体地理解2.0文档的魅力,方便开发运用到实际项目中。
Title Using Compenents(使用组件)Local Registration(局域注册)! data在模板组件?? DOM Template Parsing Caveats 一些 HTML 元素对什么元素可以放在它里面有限制。常见的限制: a 不能包含其它的交互元素(如按钮,链接) ul 和 ol 只能直接包含 li select 只能包含 option 和 optgroup table 只能直接包含 thead, tbody, tfoot, tr, caption, col, colgroup tr 只能直接包含 th 和 td
另一个结果是,自定义标签(包括自定义元素和特殊标签)不能用在 ul, select, table 等对内部元素有限制的标签内。放在这些元素内部的自定义标签将被 提到元素的外面,因而渲染不正确。
prefer using string templates whenever possible. data Must Be a Function
data MUST BE a FunctionComposing Components 组件建构props down, events up Passing Data with Props(父到子)
camelCase vs.kebab-case Dynamic Props
One-way Data Flow :msg(default),:msg.sync(double),:msg.once(once) 效果测试
注意如果 prop 是一个对象或数组,是按引用传递。在子组件内修改它会影 响父组件的状态,不管是使用哪种绑定类型。
Prop验证
Custom Events--定制事件,子向父通信
每个 Vue 实例都是一个事件触发器:
使用 $on() 监听事件;
使用 $emit() 在它上面触发事件;
使用 $dispatch() 派发事件,事件沿着父链冒泡;
使用 $broadcast() 广播事件,事件向下传导给所有的后代。
{{ total }}
Binding Native Events to Components
Form Input Components using Custom Events
This interface can be used not only to connect with form inputs inside a component, but also to easily integrate
input types that you invent yourself. Imagine these possibilities:
{{ message }}
v-model="message"
父组件模板的内容在父组件作用域内编译;子组件模板的内容在子组件作用域内编译
Non Parent-Child Communication
Content Distribution with Slots(内容分发)
Hello Vue.js!
slot 其实只是个替补
无则上位
header
main
custom header
Dynamic Components
如果把切换出去的组件保留在内存中,可以保留它的状态或避免重新渲染
Misc 杂项
Authoring Reusable Components:编写可复用组件
在编写组件时,记住是否要复用组件有好处。一次性组件跟其它组件紧密耦合没关系,
但是可复用组件应当定义一个清晰的公开接口。
Vue.js 组件 API 来自三部分——prop,事件和 slot:
prop 允许外部环境传递数据给组件;
事件 允许组件触发外部环境的 action;
slot 允许外部环境插入内容到组件的视图结构内。
使用 v-bind 和 v-on 的简写语法,模板的缩进清楚且简洁
!--@event-a="doThis"--
!--@event-b="doThat"-->
Async Components:异步组件
在大型应用中,我们可能需要将应用拆分为小块,只在需要时才从服务器下载。为了让事情更简单,Vue.js 允许将组件定义为一个工厂函数,动态地解析组件的定义。Vue.js 只在组件需要渲染时触发工厂函数,
并且把结果缓存起来,用于后面的再次渲染。
Component Naming Conventions
Recursive(递归) Components
Inline Templates
如果子组件有 inline-template 特性,组件将把它的内容当作它的模板,而不是把它当作分发内容。这让模板更灵活。
但是 inline-template 让模板的作用域难以理解。
These are compiled as the component's own template.
Not parent's transclusion content.
这些被编译为组件自己的模板,而非父组件的过渡内容
X-Templates
这在有很多模版或者小的应用中有用,否则应该避免使用,因为它将模版和组件的其他定义隔离了。
Cheap Static Components with v-once:一次性组件
当组件中包含大量静态内容时,可以考虑使用 v-once 将渲染结果缓存起来
Rendering plain HTML elements is very fast in Vue, but sometimes
you might have a component that contains a lot of static content.
In these cases, you can ensure that it’s only evaluated once(只评估一次) and then cached by
adding the v-once directive to the root element, like this: