vue3基础一

一、组合式API
 父组件:通过$refs获取子组件的相关信息,如果子组件非语法糖写法,则所有的属性和方法都会暴露给父组件

<template>
  <div class="parent-container">
    <h2>我是父元素</h2>
    <div> 房子: {{ house }} 套</div>
    <button @click="handleGetAllChild($refs)">获取所有子组件</button>
    <button @click="handleChangeAllChildBooks($refs)">更改子组件中书本的数量</button>
    <Child1 ref="c1"></Child1>
    <hr>
    <Child2 ref="c2"></Child2>
  </div>
</template>

<script lang="ts">
import Child1 from './Child1.vue';
import Child2 from './Child2.vue';
import { ref } from 'vue'
export default {
  name: 'ParentBox',
  components: {
    Child1,
    Child2
  },
  setup() {
    let house = ref(4);
    const handleGetAllChild = (refs) => {
      console.log(refs,'refs')
    };
    const handleChangeAllChildBooks = (refs) => {
      for(let key in refs) {
        refs[key].book += 3
      }
    }
    return {
      house,
      handleGetAllChild,
      handleChangeAllChildBooks
    }
  }
} 
</script> 

<style scoped>
.parent-container {
  background-color: aliceblue;
  padding: 10px;

}
</style>

 

父组件语法糖写法,通过defineExpose方法,将对象和方法暴露出去

<script lang="ts" setup name="ParentBox">
import { ref, defineExpose  } from 'vue'
import Child1 from './Child1.vue';
import Child2 from './Child2.vue';
let house = ref(4);
    const handleGetAllChild = (refs) => {
      console.log(refs,'refs')
    };
    const handleChangeAllChildBooks = (refs) => {
      for(let key in refs) {
        refs[key].book += 3
      }
    }
    defineExpose({house})
</script>

  

子组件1

<template>
  <div class="child-container">
  子元素1
  <div>玩具: {{ toy }}</div>
  <div>书本: {{ book }}本</div>
  <button @click="handleChangeParent($parent)"> 获取父元素</button>
  </div>
</template>

<script lang="ts">
import {ref} from "vue"
export default {
  setup() {
    let toy = ref('库洛米');
    let book = ref(3);
    const handleChangeParent = (parents) => {
      console.log(parents)
      parents.house--
    }
    return {
      toy,
      book,
      handleChangeParent
    }
  }
}
</script>

<style scoped>
.child-container {
  background-color: darkkhaki;
  padding: 10px;
  border-radius: 4px;
}

</style>

  

子组件2

<template>
  <div class="child-container">
    子元素2
    <div>
      零食: {{ broadBean }}袋
    </div>
    <div>
      书本: {{ book }}本
    </div>
  </div>
</template>

<script lang="ts">
import { ref } from 'vue'
export default {
  setup(){
    let broadBean = ref(5)
    let book = ref(5)
    return {
      broadBean,
      book
    }
  }
}
</script>

<style scoped>
.child-container {
  background-color: darkkhaki;
  padding: 10px;
  border-radius: 4px;
}
</style>

  

posted @ 2024-11-11 20:33  小小07  阅读(1)  评论(0编辑  收藏  举报