children
<div id="app">
<cpn></cpn>
<button @click="btnclick()" > 按钮 </button>
</div>
<template id="son">
<div>
<ul>
<li v-for="item in books" > {{item}} </li>
</ul>
<span v-show = "isshow">{{message}} </span>
</div>
</template>
<script>
const cpn ={
template:`#son`,
data (){
return {
message:'hello,world',
books:['82年生的金智英','你当像鸟飞向你的山','书店日记','时间的秩序','喜鹊谋杀案'],
isshow:false
}
},
methods:{
showmessage() {
this.isshow=true;
}
}
}
const app = new Vue({
el:'#app',
data:{
books:['82年生的金智英','你当像鸟飞向你的山','书店日记','时间的秩序','喜鹊谋杀案'],
},
methods:{
btnclick(){
console.log(this.$children[0])
this.$children[0].showmessage()
}
},
components:{
cpn
}
})
</script>
refs
<div id="app">
<cpn></cpn>
<cpn ref="aaa" ></cpn>
<button @click="btnclick()" > 按钮 </button>
</div>
<template id="son">
<div>
<div>1</div>
<span v-show = "isshow">{{message}} </span>
</div>
</template>
<script>
const cpn ={
template:`#son`,
data (){
return {
message:'hello,world',
isshow:false
}
},
methods:{
showmessage() {
this.isshow=true;
}
}
}
const app = new Vue({
el:'#app',
methods:{
btnclick(){
console.log(this.$refs.aaa);
this.$refs.aaa.showmessage()
}
},
components:{
cpn
}
})
</script>
<div id="app">
<cpn></cpn>
</div>
<template id="son">
<div>
<div>
我是子组件
</div>
<button @click="btnclick">按钮 </button>
</div>
</template>
<script>
const cpn ={
template:`#son`,
methods:{
btnclick(){
console.log(this.$parent);
console.log(this.$root)
console.log(this.$parent.message);
}
}
}
const app = new Vue({
el:'#app',
data:{
message:'hello,world',
},
components:{
cpn
}
})
</script>
<div id="app">
<!--对template中的slot部分进行替换-->
<cpn><span>---左边---</span> </cpn>
</div>
<template id="son">
<div>
<slot></slot>
<span>---右边---</span>
</div>
</template>
<script>
const cpn ={
template:`#son`,
}
const app = new Vue({
el:'#app',
components:{
cpn
}
})
</script>
<div id="app">
<cpn> <span slot="left" >---左边---</span>
<span slot="center">---中间---</span>
</cpn>
</div>
<template id="son">
<div>
<slot name="left"></slot>
<slot name="center" ></slot>
<!--默认插槽内容的写法-->
<slot name="right" ><span>---右边---</span></slot>
</div>
</template>
<script>
const cpn ={
template:`#son`,
}
const app = new Vue({
el:'#app',
components:{
cpn
}
})
</script>
<div id="app">
<cpn></cpn>
<cpn>
<template slot-scope="slot">
<span v-for="item in slot.data">{{item}} </span>
</template>
</cpn>
</div>
<template id="son">
<div>
<slot :data="books">
<ul>
<li v-for="item in books" >{{item}} </li>
</ul>
</slot>
</div>
</template>
<script>
const cpn ={
template:`#son`,
data(){
return{
books:['82年生的金智英','你当像鸟飞向你的山','书店日记','时间的秩序','喜鹊谋杀案']
}
}
}
const app = new Vue({
el:'#app',
components:{
cpn
}
})
</script>