其他分享
首页 > 其他分享> > 计算属性、插槽slot、内容分发

计算属性、插槽slot、内容分发

作者:互联网

1.计算属性

测试代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<!-- methods里的方法调用要加()-->
<div>{{time1()}}</div>
<!-- computed里的属性调用-->
<div>{{time2}}</div>
</div>
</body>
<script src='https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js'></script>
<script>
var mv=new Vue({
el:"#app",
methods:
{
time1:function () {
return Date.now();
}
},
computed:{
time2:function () {
return Date.now();
}
}
})

</script>
</html>
测试结果:

 

 

2.插槽slot

如何在组件component中插入其他组件--使用插槽slot

实现步骤:

(1)写总组件,模板里写入<slot></slot>,插槽要记得起名字name

  (2) 写分组件,模板写你要插入的东西

(3)写总组件标签,里面写分组件标签,分组件标签要写对应的插槽slot=“插槽名字name”

(4)传值等操作参考正常的传递参数

测试代码:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<ig>
<theshy slot="theshy1" :igtheshy="igtop"></theshy>
<rookie slot="rookie1" v-for="igmid in igmids" :igrookie="igmid"></rookie>
</ig>
</div>
</body>
<script src='https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js'></script>
<script>
Vue.component("ig",{
template:`
<div>
<slot name="theshy1"></slot>
<ul>
<slot name="rookie1"></slot>
</ul>
</div>`
});
Vue.component("theshy",{
props:['igtheshy'],
template:`<div>{{igtheshy}}</div>`
});
Vue.component("rookie",{
props:['igrookie'],
template:`<li>{{igrookie}}</li>`
});
var mv=new Vue({
el:"#app",
data:{
igtop:"the-shy",
igmids:["rookie","肉鸡","小ig"]
}
});
</script>
</html>
测试结果:

 

3.内容分发

自定义事件使用$emit(事件名称,参数)

在分组标签里

 是@delete1不是:delete,类比@click,@自定义事件=“vue中的事件”
测试代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div id="app">
<ig>
<theshy slot="theshy1" :igtheshy="igtop"></theshy>
<!-- 是@delete1不是:delete,类比@click,@自定义事件=“vue中的事件”-->
<rookie slot="rookie1" v-for="(igmid,index) in igmids" :igrookie="igmid" :index="index" @delete="deleteigmids"></rookie>
</ig>
</div>
</body>
<script src='https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js'></script>
<script>
Vue.component("ig",{
template:`
<div>
<slot name="theshy1"></slot>
<ul>
<slot name="rookie1"></slot>
</ul>
</div>`
});
Vue.component("theshy",{
props:['igtheshy'],
template:`<div>{{igtheshy}}</div>`
});
Vue.component("rookie",{
props:['igrookie','index'],
template:`<li>{{igrookie}}------{{index}} <button @click="delete1(index)">删除</button></li>`,
methods:{
delete1:function (index) {
alert(index);
this.$emit('delete',index);

}
}

});
var mv=new Vue({
el:"#app",
data:{
igtop:"the-shy",
igmids:["rookie","肉鸡","小ig"]
},
methods:{
deleteigmids:function (index) {
this.igmids.splice(index,1);
alert(index);

}
}
});
</script>
</html>
测试结果:

 

 

 

标签:slot,index,Vue,分发,插槽,component,template,组件
来源: https://www.cnblogs.com/zcz666/p/16437537.html