vue.js 知识学完
组件可以扩展Html元素,封装可重用的代码
组件也可以是原生的Html元素,以is特性扩展
1.创建组件:
var myComponent=Vue.extend({
template : '
component content
'
})
2.注册组件:
Vue.component("tag-name",myComponent)
1和2 也可以直接写成
Vue.component({
"tag-name":{"template":'
component content
'}
})
vue.js 背后会自动调用Vue.extend()
以上就注册了一个自定义元素“tag-name”
3.组件的使用
创建vue实例
new vue({
el:"#example"
})
html代码使用
其中自定义元素部分会替换为该组件对应的template内容
自定义元素的作用只是用作一个挂载点
4.局部注册:
可以让组件只在其他组件内部使用
var child=Vue.extend({template:"
"})
var parent=Vue.extend({
template:“”,
components:{"child-tag":child }
})
只能在parent组件内使用child组件
5.模板解析
vue的模板为DOM模板。使用浏览器原生的解析器进行解析
6.Props 传递数据
可以使用props把数据传递给子组件
Vue.component("child",{
props:["myMessage"],
template:"{{ myMessage }}"
})
渲染为 :hello
7.props绑定类型
//默认单向
//双向绑定
//单次绑定
8.props可以指定验证要求
Vue.component('example', {
props: {
// 基础类型检测 (`null` 意思是任何类型都可以)
propA: Number,
// 多种类型 (1.0.21+)
propM: [String, Number],
// 必需且是字符串
propB: {
type: String,
required: true
},
// 数字,有默认值
propC: {
type: Number,
default: 100
}
}})
9.父子组件
this.$parent可以访问子组件的父组件
this.$children 父组件的所有元素
10 .自定义事件
Vue实现了一个自定义事件接口,用于组件树中通信
每个vue实例都是一个事件触发器
使用$on() 监听事件
使用 $emit() 在他上面触发事件
使用 $dispatch() 派发事件,事件沿着父链冒泡
使用 $broadcast() 广播事件,事件向下传导给所有的后代
11.slot 插槽 内容分发API
父组件的内容将被抛弃,除非子组件模板包含,如果子组件有一个slot,父组件的所有内容将查到slot所在地方 并替换
子组件(my-component )定义如下模板:
父组件模板:
this some orignal content
最后的渲染结果:
this is my component!
this some orignal content
12 .动态组件
多个组件可以使用同一个挂载点,然后动态的在他们之间切换。使用
保留的元素,动态绑定到is特性
new Vue({
el : "body",
data:{
currentView:"home"
},
components:{
home:{/* */},
posts:{/* */},
archive:{/* */}
} })
keep-alive 可以把切换出去的组件保留在内存中,可保留状态或避免重复渲染
13.两个动态组件之间的过渡(transition-mode)
in-out :新组件先进入 过渡完成之后当前组件过度出去
out-in :当前组件过渡出去,过渡完成之后新组件过渡进入
css 样式:
.fade-transition {
transition:opacity .3s ease;
}
.fade-enter , .fade-leave{
opcity:0;
}
14.组件和v-for
为了传递数据给组件,应当使用props
15.可复用组件
可复用组件应当定义一个清晰的公开接口
vue.js组件API包含三部分: prop 事件 slot
prop :允许外部数据传递给组件
事件:允许组件触发外部环境的action
slot:允许外部环境插内容到组件的视图结构中去