一个案例: 使用组件和插槽遍历表格
//需求:
将表格封装成组件,表格中的内容是循环数据得到的,每使用一次组件,通过组件与Vue对象之间的通讯,传递不同的数据,使每次遍历的表格内容不同,其中表格中的操作标题中的按钮也可以使用具名插槽设置不同的标签内容
插槽中的数据传递
// 如果在插槽中需要在组件模板外面使用组件中的数据
// 1.可以在插槽中设置自定义属性,并把数据传递出去
// 2.然后在外部#app的div中插入的标签中接收数据
// 3.如果想要打印,可以在当前插入的标签中绑定事件,并将数据传递给该事件中的方法中,此时在methods中声明方法,并设置一个形参接收,然后在方法中打印出传递的值
// 4.此时就可以在绑定的这个事件触发时,将组建中的插槽中传递的数据在外部打印出来了
//1) 在插槽中设置自定义属性向外传递数据
<slot name="插槽名" :自定义属性="组件中的数据"></slot>
eg: <slot name="s1" :id="item.id"></slot>
//2) 在插入的标签中使用slot-scope接收自定义属性中的数据,将这个数据传递给事件中的方法
<button slot="插槽名" slot-scope="自定义属性名" @click="方法名(自定义属性名)">插入内容</button>
eg: <button slot="s1" slot-scope="id" @click="del(id)">删除</button>
//3) 在methods中声明方法,并接收上面传递的数据,然后可以打印出来
methods:{
del(v){
console.log(v)
}
}
Vue2中的生命周期函数
语法格式:
new Vue({
el:'',
data:{},
methods:{},
生命周期函数(){}
})
1. beforeCreate() 创建前
2. created() 创建后
3. beforeMount() 挂载(渲染)前
4. mounted() 挂载(渲染)后
5. beforeUpdate() 修改前
6. updated() 修改后
7. beforeDestroy() 销毁前
8. destroyed() 销毁后
代码演示
<body>
<div id="app">
<div id="box">{{str}}</div>
<button @click="fun()">修改值</button>
</div>
</body>
<script>
new Vue({
el:'#app',
data:{
str:'修改前的值'
},
methods:{
fun(){
this.str='修改后的值'
}
},
//1.创建前执行的函数,此时data和methods还没有创建(自动调用)
beforeCreate(){
console.log('我是beforeCreate函数,我被执行了');
console.log(this.str); //undefined
let box=document.getElementById('box');
console.log(box.innerHTML); //{{str}}
},
//2.创建后执行的函数,此时data和methods已被创建,但没有渲染页面(自动调用)
created(){
//多用于发送ajax请求
console.log('我是created函数,我被执行了');
console.log(this.str); //修改前的值
let box=document.getElementById('box');
console.log(box.innerHTML); //{{str}}
},
//3.挂载(渲染)之前执行的函数,此时模板已经被编译,但没有渲染页面(自动调用)
beforeMount(){
console.log('我是beforeMount函数,我被执行了');
console.log(this.str); //修改前的值
let box=document.getElementById('box');
console.log(box.innerHTML); //{{str}}
},
//4.挂载(渲染)之后执行的函数,此时的页面可以被渲染(自动调用)
mounted(){
console.log('我是mounted函数,我被执行了');
console.log(this.str); //修改前的值
let box=document.getElementById('box');
console.log(box.innerHTML); //修改前的值
},
//5.修改前执行的函数,此时页面没有被渲染(需要触发事件)
beforeUpdate(){
console.log('我是beforeUpdate函数,我被执行了');
console.log(this.str); //修改后的值
let box=document.getElementById('box');
console.log(box.innerHTML); //修改前的值
},
//6.修改后执行的函数,此时页面已经被渲染(需要触发事件)
updated(){
console.log('我是updated函数,我被执行了');
console.log(this.str); //修改后的值
let box=document.getElementById('box');
console.log(box.innerHTML); //修改后的值
}
//7. beforeDestroy(), 销毁前的函数
//8. destroyed(), 销毁后的函数
})
</script>
</html>