什么是setup

setup是vue3新增的生命周期函数,setup的加入就是为了让vue3使用组合式API(Composition API)。使用组合式API更符合大型项目的开发,通过setup可以将该部分抽离成函数,让其他开发者就不用关心该部分逻辑。setup位于beforeCreated之前,用于代替created 和beforeCreated。不仅是作为vue3新增的生命周期函数,还可以在setup中引入外部js文件方法,可在js中共用vue全部生命周期。

特征

1、setup函数是处于 生命周期函数 beforeCreate 和 Created 两个钩子函数之间的函数 也就说在 setup函数中是无法 使用 data 和 methods 中的数据和方法的

2、setup函数是 Composition API(组合API)的入口

3、在setup函数中定义的变量和方法最后都是需要 return 出去的 不然无法再模板中使用

4.setup函数中的this修改成了 undefined

5.setup函数只能是同步的不能是异步的

执行时机

setup 会在 beforeCreate 之前执行。

setup 包含的生命周期

 

onBeforeMount——挂载开始前调用
onMounted——挂载后调用
onBeforeUpdate——当响应数据改变,且重新渲染前调用
onUpdated——重新渲染后调用
onBeforeUnmount——Vue实例销毁前调用
onUnmounted——实例销毁后调用
onActivated——当keep-alive组件被激活时调用
onDeactivated——当keep-alive组件取消激活时调用
onErrorCaptured——从子组件中捕获错误时调用

import { onMounted } from 'vue'
export default {
  name: "hello",
  setup(msg) {
    onMounted(()=>{
      console.log("onMounted");
    })
    console.log(msg);
    return { name:"Mr liu" };
  },
  beforeCreate(){
    console.log("beforeCreate");
  }
};

setup使用ref和reactive对数据进行响应式绑定

 

<template>
  <div class="hello">
    <h1>{{ name }}</h1>
    <h5>count:{{count}}</h5>
  </div>
</template>
<script>
import { onMounted,ref,reactive} from 'vue'
export default {
  name: "hello",
  setup(msg) {
    onMounted(()=>{
      console.log("onMounted");
    })
    console.log(msg);

    //创建定时器增加count值
    let count = ref(1);
    //reactive 变成响应式对象

    setInterval(()=>{
      count++
    },1000)
    return { name:"Mr liu",count:count };
  },
  beforeCreate(){
    console.log("beforeCreate");
  }
};
</script>
<style scoped>
</style>

 

setup使用watch和computed

 

count
使用 computed 计算count的值:
    let count2 = computed(()=>count.value*2);
    return { name: "Mr liu", count: count2 };

 

我们可以将代码分成多个部分并引入:

新建 mycount.js 文件:
import { ref } from 'vue'
export default function mycount(){
    //创建定时器增加count值
    let count = ref('1');
    setInterval(()=>{
        count.value++
    },1000)
    return{
        count:count
    }
}

引入 mycount 文件:

import mycount from '../../util/count';
export default {
  name: "hello",
  setup() {
    let {count} = mycount();
    return { name: "Mr liu" ,count};
  },
  beforeCreate() {
    console.log("beforeCreate");
  },
};

关于 props 的值

 

父组件给子组件传值 user:'anny'

子组件setup可以取出该值:
import mycount from '../../util/count';
export default {
  name: "hello",
  props:{
    user:String
  },
  setup(msg) {
    console.log(msg.user)
    let {count} = mycount();
    return { name: "Mr liu" ,count};
  },
  beforeCreate() {
    console.log("beforeCreate");
  },
};

 

setup 参数

「props」第一个参数接受一个响应式的props,这个props指向的是外部的props。如果你没有定义props选项,setup中的第一个参数将为undifined,不要在子组件中修改props;如果你尝试修改,将会给你警告甚至报错;不要解构props。结构的props会失去响应性。

「上下文对象」第二个参数提供了一个上下文对象,从原来 2.x 中 this 选择性地暴露了一些 property。