模版is特性
<tr is="parent"></tr>
组件传递数据
Vue.component('parent',{ template:'Hello{{msg}}', props:['msg'] });
父子组件不能通用属性 属性采用-线,props采用驼峰命名
动态绑定Props
动态绑定
:msg-com="hello"
注意
<!-- 传递了一个字符串 "1" --> <comp some-prop="1"></comp> <!-- 传递实际的数字 --> <comp :some-prop="1"></comp>
props验证
设置双向绑定
<parent :msg.sync="hello"></parent>
验证规则
msg:{ type:[String, Number], //String Number Object Function Boolean Array default: function () { return {name:1} }, twoWay:true, validator: function (v) { return v==1; //不成立报错 }, coerce: function (val) { return val; //在赋值前进行操作 } }
父子组件的通信事件
? $broadcast向下传导给所有后代
? $dispatch沿父链冒泡(包括自己)
? $emit在本身触发
父子组件的通信事件
var parent = Vue.extend({ template:'##parent', methods:{ parent: function () { this.$broadcast('broad','爸爸被点击了');} }, events:{ emit: function (data) {alert(data);} }, }); var child = Vue.extend({ template:'##child', events:{ broad: function (data) {alert(data);}, self: function (data) {alert(data);} }, methods:{ child: function () { this.$dispatch('emit','儿子被点击了'); this.$emit('self','自己被点击了'); } } }); Vue.component('parent',parent); Vue.component('child',child);
子组件索引
通过v-ref拿到当前组件
<div id="parent"> <user-profile v-ref:p></user-profile> </div> var parent = new Vue({el:'##parent'}); console.log(parent.$refs.p);
嵌套内容
嵌入组件中的内容
<user-profile> <div>123</div> <div>456</div> </user-profile> template:"<div>789</div><slot></slot>"
嵌套内容指定名字
<user-profile> <div slot="name">123</div> <div slot="age">456</div> <div slot>890</div> </user-profile> template:"<div>789</div><slot name='age'></slot><slot name='name'></slot><slot></slot>"
动态引用模版
自带的component元素
<component :is="current"></component>
切换components
var parent = new Vue({ el: '##parent', data:{ current:'home' }, components:{ home:{ template:'<div>12</div>' }, age:{ template:'<div>34</div>' } } });
数据响应
通过实例设置数据并响应
setTimeout(function () { parent.$set('bug',100); },2000)
通过全局对象设置
var data = {} var parent = new Vue({ el: '##parent', data: data }); //parent.bug = 100; //无法响应 Vue.set(data,'bug',500)
异步设置数据
下一事件环
parent.bug = 100; parent.$el.innerHTML==='100';//无法立即获得数据 Vue.nextTick(function () { console.log( parent.$el.innerHTML==='100'); })
computed深入用法
默认缓存机制
var data = {} var parent = new Vue({ el: '##parent', data:{ bug:'', timer:'' }, computed:{ mess:{ cache: false, //默认为true get: function () { return new Date(); } } } }); setInterval(function () { parent.$set('timer',parent.mess); },1000);