Vue3.2中setup语法糖的基本使用

379 阅读1分钟

1.setup语法糖的基本理解

  • 开始Vue3.0中想用变量的时候必须用 return出来才可以在 template使用
  • 用了Vue3.2框架现在只需要在script标签中添加setup就可以,定义的属性和方法也可以不用想着去return返回,就连export default也可以省略,还有自定义指令也可以直接在template中获取

setup定义变量和方法 ref和reactive

  1. 使用简单基本数据类型的时候用(String,Number)推荐用 ref 但是也可以用 reactive
  • 首先引入:import { ref } from 'vue'
  • const count = ref(1)
  1. 使用简单复杂数据类型的时候用(Array,Object)推荐用 reactive 但是也可以用 ref
  • 首先引入:import { reactive } from 'vue'
  • const count = reactive({age:18})

setup代替了那些声明周期

image.png


import {
  onBeforeMount,
  onMounted,
  onBeforeUpdate,
  onUpdated,
  onBeforeUnmount,
  onUnmounted
} from 'vue'
  // 挂在前
  onBeforeMount(()=>{
    console.log('挂在前');
  })

  // 挂在后
  onMounted(()=>{
    console.log('挂在后');
  })
  
  // 数据更新前
  onBeforeUpdate(()=>{
    console.log('更新前');
  })

  // 更新后
  onUpdated(()=>{
    console.log('更新后');
  })

  // 销毁前
  onBeforeUnmount(()=>{
    console.log('销毁前');
  })

  // 销毁后
  onUnmounted(()=>{
    console.log('销毁后');
  })

setup自动注册组件 vue3语法在引入Child组件后,需要在components中注册对应的组件才可使用。 但是vue3 用了setup就放便很多了

<script setup>
    //在script里面可以直接引用
    import child from './Child.vue'
</script>

setup父子传值 defineProps defineEmits

defineProps在子组件接收值用

    //父组件
    <template>
      <div class='father'>
          <h1>我是父组件</h1>
          <child :name='name'></child>
      </div>
    </template>

    <script setup>
        import child from './Child.vue'
        import {ref} from 'vue'
        const name=ref('我是父组件传给子组件的值')
    </script>
    //子组件
<template>
  <div class="chlid">
      <h2>我是子组件</h2>
      
      <!-- 第一种接收值 -->
      <p>{{data.name}}</p>
      
      <!-- 第二种接收值 -->
      <p>{{name}}</p>
  </div>
</template>

<script setup>
import {defineProps} from 'vue'
    // 第一种接收值得方法
    const data=defineProps(['name'])

    // 第二种接收值得方法
    //  defineProps({
    //     name:{
    //         type:String,
    //         default:'我是默认值'
    //     }
    //  })
</script>

defineEmits触发子组件修改父组件的值

<template>
  <div class="father">
      <h1>我是父组件</h1>
      <child @setBtn='data'></child>
      {{name}}
  </div>
</template>

<script setup>
    import child from './Child.vue'
    import {ref} from 'vue'
    const name=ref('')
    const data=(v)=>{
        name.value=v
    }
</script>
<template>
  <div class="chlid">
    <h2>我是子组件</h2>
    <button @click="Btn">点击修改父组件的值</button>
  </div>
</template>

<script setup>
    import {defineEmits} from 'vue'
    const emit=defineEmits(['setBtn'])

    const Btn=()=>{
        emit('setBtn','我是子组件传过来的值')
    }
</script>

1 (35).jpg