组件
什么是组件?
组件就是局部功能,一个页面可以拆分成多个组件,在通多命令行程序cli构建的vue程序中,一个.vue文件就是一个组件
.vue文件构成?
三大部分:<template>,<script>,<style>
组件的功能?
易于维护,减少冗余,代码复用,组件可以嵌套使用,在一个组件中可以引入另外的组件如
现有文件 a.vue 和 b.vue(二者在同一目录下),在a组件中引入b组件,就在a组件的script中加入
import b from 'b'; //引入
export default {
components : { b }, //声明
}
在template中使用 <b />标签即可使用 , 一个示例代码(App组件)
<template>
<div class="app">
<!-- 使用组件top-->
<top :add="add"/>
<!-- 使用组件center-->
<center :msg="msg" :del="del"/>
<!-- 使用组件bottom-->
<bottom :msg="msg" :del_selected="del_selected"/>
</div>
</template>
<script>
import top from './components/top'; //引入组件 top
import center from './components/center'; //引入组件 center
import bottom from './components/bottom'; //引入组件 bottom
export default {
components:{
top , center , bottom
}
}
</script>
<style scoped>
.app{
width: 60%;
margin: 0 20% 0 20%;
height: auto;
}
</style>
组件间通信
组件间通信是父组件向子组件传递消息 , 故一般几个组件共有数据放在他们的父组件中 , 传递消息采用给标签添加属性的方式进行传递 , 在被传递消息的组件中 , 通过 props 属性 进行消息传递的声明 , 下面是 两个示例组件 , c组件要向d组件传递自己的数据和方法
c.vue
<template>
<div class="c">
<p>im c</p>
<d :msg="msg" :change="change"/> //使用d组件 , 传递数据和change方法
</div>
</template>
<script>
import d from './d'; //引入d组件
export default {
components : { d }, //声明d组件
data(){
return {
msg : 'i from c' //初始化数据
}
},
methods : {
change(){ //声明函数
this.msg = 'i change msg from c';
console.log(this.msg);
}
}
}
</script>
<style scoped>
.c{ //样式
height: 200px;
width: 100px;
background: red;
}
</style>
d.vue
<template>
<div class="d">
<p>im d</p>
<p>{{msg}}</p> //使用c组件传递的数据
<button @click="change">改变msg</button> //使用c组件传递的函数
</div>
</template>
<script>
export default {
props:{ //props属性用于声明,传递进来的数据及类型
msg : String, //msg是string
change : Function //change是function
}
}
</script>
<style scoped>
.d{ /样式
height: 100px;
width: 100px;
background: blue;
}
</style>
示例截图:
初始化的页面
点击按钮触发事件
数组的深度监视
一般来说,对数组进行监视,只会发现数组的改变,不能发现数据的改变,比如说有数组a
a.pop ,a.shift , a=b 等都能监视到
但是 a[1]=xxx就不能监视的到
这时候在watch属性中加一个deep:true即可 示例如下:
watch : {
test : { // 被监视的对象
deep : true , //深度监视
handler(){ //句柄,回调函数
console.log('i see change');
}
}
}