父组件:
<template>
<div class="box">
<Header >
<div slot="left">你好</div>
<div slot="right" @click="userFn">你好</div>
</Header>
<div class="content">
<h1 ref="title" id="title">标题</h1>
<p ref="desc" id="desc">段落描述</p>
<button @click="getDOM">获取DOM节点</button>
<Reftest ref="test"/>
<button @click="getData">获取子元素数据</button>
</div>
</div>
</template>
<script>
import Header from '@/mixins/header'
import Reftest from '@/mixins/header'
export default {
mixins:[Header,Reftest],
data(){
return {
message:'父组件'
}
},
methods: {
getDOM () {
console.log(document.getElementById('title'))
console.log(document.getElementById('desc'))
console.log('----------------------')
console.log(this.$refs.title)
console.log(this.$refs.desc)
},
getData(){
this.$refs.test.msg='奶牛'
console.log(this.$refs.test.msg)
},
}
}
</script>
子组件
<template>
<header class="header">
<ul>
<li>
<slot name="left">左</slot>
</li>
<li>
<slot>中</slot>
</li>
<li>
<slot name="right">右</slot>
</li>
</ul>
</header>
</template>
<style lang="scss">
.header {
width: 100%;
height: 44px;
background-color: #f66;
margin-bottom: 10px;
ul {
width: 100%;
height: 100%;
display: flex;
li{
width: auto;
height: 100%;
display: flex;
justify-content: center;
align-items: center;
&:nth-child(1) {
width: 50px;
}
&:nth-child(2) {
flex: 1;
}
&:nth-child(3) {
width: 50px;
}
}
}
}
</style>
<template>
<div>
<button @click="getData">子组件直接获取父组件的数据</button>
</div>
</template>
<script>
export default {
data () {
return {
msg: 'child-----------------------------'
}
},
methods: {
getData () {
console.log(this.$parent.message)
}
}
}
</script>
Header.js
import Header from '@/components/Header'
import Reftest from '@/components/Reftest'
export default {
components: {
Header,
Reftest
},
methods: {
userFn () {
console.log('个人中心')
}
}
}
长风破浪会有时,直挂云帆济沧海