Vue3中 setup 语法糖用法及父子组件传值

1,418 阅读1分钟

开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第4天

vue3中在script标签中添加setup,可以不用写setup函数,不用写export default,也不需要return出去, 组件只需要引入不需要注册。

以下举例:

  • 在script setup中,不需要在引入组件后,通过 components:{}注册组件,可直接使用。
  • 示例:
<template>
  <div class="home">
    <h1>这是首页这是父组件</h1>
    // 引入的子组件
    <Child/>
  </div>
</template>
<script setup lang="ts">
import Child from '@/views/Child.vue'  // < script setup>引入组件将自动注册
</script>
  • 组件之间的通信,vue2使用props和emit
  • vue3中setup script语法糖提供了新的API使用:defineProps 用来接收父组件传来的 props,defineEmits 用来声明触发的事件
  • 示例:父向子传值
//父组件
<template>
  <div class="home">
    <h1>这是父组件</h1>
    //Child 是子组件
    <Child :valueData="msg"/>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import Child from '@/views/Child.vue'
const msg = ref('这是父组件传过来的值噢')  //自动返回,在template使用
</script>
// 子组件
<template>
  <div>
    <div>父组件传递过来的值: {{valueData}}</div>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue'
// 语法糖必须使用defineProps替代props
const props = defineProps({
  valueData: {
    type: String
  }
})
// 需要通过props.xx获取父组件传递过来的值
console.log(props.valueData) // 这是父组件传过来的值噢
<script>
  • 示例:子组件向父组件传值
  • defineEmit 代替emit,子组件向父组件传递数据
//子组件
<template>
  <div>
      <button @click="toEmit">子组件向外暴露数据</button>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue'

const nameval = ref('我是儿子哦')
// defineEmit 代替emit,子组件向父组件传递数据(子组件向外暴露数据)
const emits = defineEmits(['childClick'])
// 点击事件 向父组件传值
const toEmit = () =>{
  // 触发父组件事件childClick并携带参数
  emits('childClick', nameval)
}
// 父组件
<template>
  <div class="home">
    <h1>这是父组件</h1>
    <Child @childClick="childValFn"/>
    <p>
      接收子组件传递的数据:
      <h1>{{childData}}</h1>
    </p>
  </div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import Child from '@/views/Child.vue'

const childData = ref(null)
// 父组件传递过来事件
const childValFn = (e:any)=>{
    //接收子组件传递给父组件的值
    childData.value = e.value
}
</script>