Vue3.x语法糖setup和组件传参相关API的使用

本文详细介绍了Vue3.x中script-setup语法糖的使用,包括组件自动注册、defineProps接收props、defineEmits处理父子组件事件、defineExpose暴露属性以及useAttrs获取额外属性。通过实例展示了如何在组件间传递数据和触发事件,帮助开发者更好地理解和应用Vue3.x的新特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Vue3.x语法糖setup和组件传参相关API的使用

前言:随着Vue3.2版本的更新,script-setup语法糖也随之产生,免去了写setup函数和export default的繁琐步骤,自定义指令可以直接获得并使用,文章侧重于组件以及组件传参使用,响应式相关内容详见文档Vue3文档

1.组件自动注册

  • 区别于Vue2.x,使用script setup语法糖后,引入自定义组件时可以免去components注册的过程,直接引入组件,需要注意不能使用name属性修改组件名称了,实例如下:

    <template>
        <Count></Count>
    </template>
    <script setup>
        import Count from '../components/Count.vue'
    </script>
    

2.defineProps的使用

  • defineProps用来接收父组件传来的props

  • 父组件代码:

    <template>
        <p>父组件</p>
        <Count :count="num"></Count>
    </template>
    <script setup>
        import Count from '../components/Count.vue'
        import { ref } from 'vue'
        let num = ref(666)
    </script>
    
  • 子组件代码:

    <template>
        <div>
          子组件{{ count }}
        </div>
    </template>
    <script setup>
      import { defineProps } from 'vue'
    
      defineProps({
       count:{
         type: Number,
         default: 6
       }
     })
    </script>
    

3.defineEmits的使用

  • 子组件向父组件事件传递(子组件触发父组件事件)

  • 父组件代码:

    <template>
        <p>父组件</p>
        <Count @handleEvent="showData"></Count>
    </template>
    <script setup>
      import Count from '../components/Count.vue'
      const showData = (data) => {
        console.log(data); // 子组件触发父组件事件
      }
    </script>
    
  • 子组件代码:

    <template>
        <div>
            子组件
        	<button @click="handleEvent">触发事件</button>
        </div>
    </template>
    <script setup>
        import { defineEmits } from 'vue'
        const em = defineEmits(['handleEvent'])
        function handleEvent() {
          em('handleEvent', '子组件触发父组件事件')
        }
    </script>
    

3.1.结合definePropsdefineEmits

  • 结合definePropsdefineEmits做一个点击按钮后子组件数值+1的自定义组件

  • 父组件代码:

    <template>
        <p>父组件</p>
        <Count @handleEvent="showData" :count="num"></Count>
    </template>
    <script setup>
      import Count from '../components/Count.vue'
      import { ref } from 'vue'
      const num = ref(0)
      const showData = (data) => {
        num.value++ // 数值+1
        console.log(data); // 子组件触发父组件事件
      }
    </script>
    
  • 子组件代码:

    <template>
      <div>
        子组件数值{{count}}
        <button @click="handleEvent">触发事件</button>
      </div>
    </template>
    <script setup>
    import { defineEmits, defineProps } from 'vue'
    defineProps({
      count: {
        type: Number,
        default: 0,
      }
    })
    const em = defineEmits(['handleEvent'])
    function handleEvent() {
      em('handleEvent', '子组件触发父组件事件')
    }
    </script>
    

4.defineExpose的使用

  • 将组件中自己的属性暴露,在父组件中能够拿到

  • 父组件代码:

    <template>
        <List ref="sonRef"></List>
        <button @click="getSonData">获取子组件暴漏的值</button>
    </template>
    <script setup>
        import List from '../components/list.vue'
        import { ref } from 'vue'
        const sonRef = ref()
        function getSonData() {
          console.log('子组件中ref暴漏的数值', sonRef.value.sonNum) // 子组件中ref暴漏的数值 0
          console.log('子组件中reactive暴漏的字符串', sonRef.value.sonName.name) // 子组件中reactive暴漏的字符串 小明
        }
    </script>
    
  • 子组件代码:

    <template>
      <div class="list-card">
        这是子组件
      </div>
    </template>
    <script setup>
        import { defineExpose, reactive, ref } from 'vue'
        let sonNum = ref(0)
        let sonName = reactive({
          name: '小明'
        })
        defineExpose({
          sonNum,
          sonName
        })
    </script>
    

5.useAttrs的使用

  • 父组件传递给子组件的属性中除了propsclassstyle外的属性

  • 父组件代码:

    <template>
        父组件
        <List a="1" b="2"></List>
    </template>
    <script setup>
        import List from '../components/list.vue'
    </script>
    
  • 子组件代码:

    <template>
        子组件
    </template>
    <script setup>
        import { useAttrs } from 'vue'
        const attrs = useAttrs()
        console.log(attrs)
    </script>
    
  • 打印结果如下:

在这里插入图片描述

6.provideinject的使用

  • 组件树中跨越多个层级数据传递,props只能一层一层传递,provideinject允许在祖先和子孙组件之间共享数据,避免了中间组件需要显式传递props
  • 祖先组件代码:
<template>
  <ChildComponent />
</template>
<script setup>
import { provide } from 'vue';
const shareString = "来自父组件的数据";
// provide提供数据
provide('sharedData', shareString);
</script>
  • 子孙组件代码:
<template>
  <p>{{ data }}</p>
</template>
<script setup>
import { inject } from 'vue';
// inject接受祖先组件提供的键shareData中的数据值
const data = inject('sharedData');
</script>

7.Pinia的使用

  • 区别于以上Composition APIPinia是一个的counter store
  • 安装Pinia
npm install pinia
  • 创建store
// stores/counter.js
import { defineStore } from 'pinia';
export const useCounterStore = defineStore('counter', {
// state定义状态
  state: () => ({
    count: 0
  }),
  // actions定义业务逻辑
  actions: {
    calculate() {
      this.count++;
    }
  }
});
  • 组件中使用Pinia
<template>
  <div>
    <p>Current Count: {{ count }}</p>
    <button @click="calculate">calculate</button>
  </div>
</template>
<script setup>
import { useCounterStore } from './stores/counter';
const counterStore = useCounterStore();
const { count, calculate} = counterStore;
</script>
  • 子组件通过emitupdate事件实现与父组件的数据同步,形成双向绑定的效果

以上就是Vue3.x中和组件相关API的使用与demo实例,欢迎补充与讨论🌈

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值