mixins使用混入引入组件,并可以使用公共函数。组件类同名函数可以替代公共函数。使用$ref获得子元素数据和元素dom节点。使用$parents获得父元素数据。slot插槽的使用

父组件:

<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('个人中心')
    }
  }
}

猜你喜欢

转载自www.cnblogs.com/hy96/p/12195131.html