index.vue 1.68 KB
<script setup lang="ts">
  import {ref, reactive} from 'vue'
  const count = ref(100)
  const obj = reactive({
    name: 'Tom',
    age: 15,
    addr: 'Beijing',
  })
  interface Props {
    maxSize?: number,
    limit?: boolean,
    collections?: string[],
    title: string
  }
  const props = withDefaults(defineProps<Props>(), {
    maxSize: 500,
    limit: false,
    collections: () => ['邮票', '唱片'],
    title: ''
  });



  const singleFunc = () => {
    console.log('组件中的单独一个方法')
  }
  const addCount = () => {
    count.value = count.value + 19
  }
  // 把该组件内的数据、函数等暴露给上级页面
  defineExpose({
    count,
    addCount,
    singleFunc
  });

  const emitFunc = () => {
    console.log('专门用来emit的方法')
    emit('emitFunc', count.value)
  }
  const emit= defineEmits<{
    (e: 'emitFunc', str: number): void,
    (e: 'update:title', str: number | string): void,
  }>()
</script>

<template>
  <div style="background-color: cyan; padding: 10px;" @click="emitFunc">
    <p>这是一个组件的内部</p>
    <div style="background-color: pink">
      <p>粉色div里面展示的是组件内的数据data</p>
      <p>{{count}}</p>
      <p>{{obj.name}}</p>
      <el-button type="primary" @click="singleFunc">组建中单独方法</el-button>
    </div>

    <div style="background-color: gold" @click="$emit('update:title', props.title)">
      <p>金色div里面展示的是组件内的属性prop</p>
      <p>{{props.limit}}</p>
      <p>{{props.collections}}</p>
      <p>{{props.maxSize}}</p>
      <p>{{props.title}}</p>
      <el-input v-model="title" @change="$emit('update:title', $event)"></el-input>
    </div>
  </div>
</template>