1.防止因网络慢,页面加载出现 {{变量名}} 的情况:
使用 v-cloak 指令,注意要在 css中 声明:
<style type='text/css'>
[v-cloak]{
display: none;
}
</style>
<div v-cloak>{{message}}</div>
组件篇
:is的理解:
例如在ul 中只能是 li ,select中只能是option ,如果需要 在 vue中实现:
<ul>
<my-li></my-li>
</ul>
类似这样的自定义组件效果,那么就需要使用is,使用方法:
<ul>
<li :is="my=li"></li>
</ul>
1.注册组件:
Vue.component('my-component',选项); 组件名: 建议使用 烤串命名,
1.参数选项注意事项:
①.必须有template或render,否则报错
②.模板必须只能有一个根元素
③.template是组件要渲染的html
④.确保要在初始化根实例之前定义好组件
2.data 必须是函数,
(为什么必须要使用工厂函数?如果使用对象的形式,多个组件可以改变同一个对象,使用函数,可以返回一个新的对象,不互相引用。)
Vue.全局注册 和局部注册两种:
全局注册
Vue.component("custom-compont",{
template:"<div>diy...</div>",
data:function(){
return {
list:[1,2,4]
};
}
});
局部注册:
//模板:
<div id='app'>
<my-component></my-component>
</div>
//JS部分:
new Vue({
el:'#app',
component:{
'my-component':{
template:"<div>局部注册组件:<component-child></component-child></div>",
components:{ //组件中还可以继续注册局部组件
"component-child":{
template:"<p>我是my-component的子组件</p>"
}
}
}
},
});
2.组件中的 props:
通信的理解:
组件意味着协同工作, 通常父子组件是这样的关系:
组件A在它的模板中,使用了组件B。它们之间必然需要相互通信,父组件要给子组件传递数据,而子组件要将内部发生的事情,告诉给父组件。
在VueJs中, 父组件通过props向下传递 数据, 而子组件通过 时间 event 给父组件发送消息。
开发中的注意事项:
1.组件的 props 命名方式,全部使用 烤串命名。 例如: props:['error-msg']
2.不能在组件内部,修改传递过来的 props 的 (非引用类型)值
3.当子组件需要改变props的值时, 那么需要绑定一个自定义事件, 在事件内部,通知父组件,让父组件去改变数据
代码说明:
<my-component @increment="parentIncrement" :notice-msg="message" @click.native="nativeEvent"></my-component>
</div>
<script type="text/javascript">
new Vue({
el: "#demo",
data: {
message: 1
},
components: {
'my-component': {
props: ['notice-msg'],
template: '<div>{{noticeMsg}}<input type="button" value="添加" @click="increment" /></div>',
methods: {
increment: function () {
//下面这种写法 是错误的,不能在组件内部修改 props
//this.noticeMsg++;
//子组件已经和它外部完全解耦了。它所做的只是触发一个父组件关心的内部事件
this.$emit('increment');
}
}
}
},
methods: {
parentIncrement: function () {
console.log('我是父组件定义的添加方法,我在原生click方法之前调用...');
this.message++;
},
nativeEvent: function () {
console.log('我是click原生监听');
}
}
});
</script>
3.组件中的 slot:
slot 翻译过来是 插槽的意思,知乎上看到一个贴切的解释:

另外需要补充说明:
什么时候我们需要使用slot?
1.当我们想在自定义组件里,嵌套组件(可以是HTML标签,也可以是自定义组件)
2.想实现组件内部为空时的提示信息
3.嵌套的组件,根据业务逻辑自定义摆放位置
如果有以上需求等,就需要使用到 slot.
个人对slot的理解:
1.典型的插槽【匹配到对应的位置就替换掉,指定name的slot标签,如若没有匹配到,会被抛弃,但也不会报错】
2.空的 <slot>标签,会将组件内部,没有声明 slot 属性的 所有元素,全部插入进去
--未完待续--
网友评论