【Vue3 从入门到实战 进阶式掌握完整知识体系】030-Composition API:Setup函数的使用

245 阅读1分钟

六、Composition API

组合 API ,即将数据和业务逻辑放在一起处理,而不是像vue2,将数据放在data中,业务逻辑分别放在methods,watch,computed中等

1、Setup函数的使用

Setup函数的执行时机:在 beforeCreate 之前执行;

代码

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>hello vue</title>
  <!-- 引入Vue库 -->
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
  <div id="root"></div>
</body>

<script>

  const app = Vue.createApp({
    // 在模板里面,可以使用 setup 函数里面提供的属性和方法
    // 因为 setup 在实例创建之前就已经执行了
    template: `
      <div @click="handleClick">name: {{name}} age: {{age}}</div>
    `,
    // 简单使用 setup 函数
    // setup 函数是在实例创建之前执行的(在 `beforeCreate` 之前)
    // setup 里面不能使用 this 关键字,因为此时实例尚未创建,不存在 this
    setup(props, context){
      return{
        name: 'zibo',
        age: 25,
        handleClick(){
          console.log("点击了");
        }
      }
    }
  });

  const vm = app.mount('#root');
</script>

</html>

运行结果

image-20210614161402715

setup内部更多写法

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>hello vue</title>
  <!-- 引入Vue库 -->
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
  <div id="root"></div>
</body>

<script>

  const app = Vue.createApp({
    // 在模板里面,可以使用 setup 函数里面提供的属性和方法
    // 因为 setup 在实例创建之前就已经执行了
    // 再次提醒:当多个函数的时候要使用括号
    template: `
      <div @click="handleClick(), add(100), changeStudentName('大哥刘备')">name: {{name}} age: {{age}}</div>
    `,
    // 简单使用 setup 函数
    // setup 函数是在实例创建之前执行的
    // setup 里面不能使用 this 关键字,因为此时实例尚未创建,不存在 this
    setup(props, context){
      const { reactive } = Vue;

      // 写法一:数据和逻辑分离
      const name = "zibo";
      const age = 25;
      // 函数写法一
      const handleClick = () => {
        console.log("点击了");
      }
      // 函数写法二
      function add(num){
        console.log("数字是:" + num);
      }
      // 写法二:数据和逻辑写在一起
      function test01(){
        // 数据
        const student = reactive({
          name: 'zibo',
          age: 25
        });
        // 逻辑
        function changeStudentName(name){
          student.name = name;
          console.log("student", student);
        }
        return { student, changeStudentName};
      }
      // 从 test01 中拿
      const {student, changeStudentName} = test01();
      return{
        name,
        age,
        handleClick,
        add,
        student,
        changeStudentName
      }
    }
  });

  const vm = app.mount('#root');
</script>

</html>

运行结果

image-20210615175607740

Composition API 和 Options API 中的同名属性

此时Options API 中的同名属性会失效

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>hello vue</title>
  <!-- 引入Vue库 -->
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
  <div id="root"></div>
</body>

<script>

  const app = Vue.createApp({
    data(){
      return{
        age: 800
      }
    },
    template: `
      <div>age: {{ age }}</div>
    `,
    setup(props, context){
      const { ref } = Vue;
      const age = ref(25);
      return{
        age
      }
    }
  });

  const vm = app.mount('#root');
</script>

</html>

运行结果

image-20210615181059947

参数props

参数 props 接收父组件传过来的参数,但是必须在当前组件中使用 props: ['属性名'] 接收,setup 才能接收到!

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>hello vue</title>
  <!-- 引入Vue库 -->
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
  <div id="root"></div>
</body>

<script>

  const app = Vue.createApp({
    template: `
      <child name="name" />
    `,
    setup(props, context){
      return{ }
    }
  });

  app.component("child", {
    // 当前组件必须使用 props 关键字接收,否则 setup 函数的 props 参数为空
    props: ['name'],
    template: `
      <h1>hello {{name}}</h1>
    `,
    setup(props, context){
      console.log(props);
    }
  });

  const vm = app.mount('#root');
</script>

</html>

运行结果

image-20210616111244209

props是响应式的

setup 中接受的props是响应式的, 当传入新的 props 时,会及时被更新。由于是响应式的, 所以不可以使用 ES6 解构,解构会消除它的响应式。

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>hello vue</title>
  <!-- 引入Vue库 -->
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
  <div id="root"></div>
</body>

<script>

  const app = Vue.createApp({
    template: `
      <child :name="name" />
      <input v-model="name" />
    `,
    setup(props, context) {
      const { ref } = Vue;
      const name = ref('zibo');
      return {
        name
      }
    }
  });

  app.component("child", {
    props: ['name'],
    template: `
      <h1>hello {{name}}</h1>
    `,
    setup(props, context) {
      const { watchEffect } = Vue;
      watchEffect(() => {
        console.log(`name is: ` + props.name)
      })
    }
  });

  const vm = app.mount('#root');
</script>

</html>

运行结果

image-20210616113057801

使用ES6解构props

与下面”解构对象的属性不是响应式的“类似,但那个是对自定义属性的解构

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>hello vue</title>
  <!-- 引入Vue库 -->
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
  <div id="root"></div>
</body>

<script>

  const app = Vue.createApp({
    template: `
      <child :name="name" />
      <input v-model="name" />
    `,
    setup(props, context) {
      const { ref } = Vue;
      const name = ref('zibo');
      return {
        name
      }
    }
  });

  app.component("child", {
    props: ['name'],
    template: `
      <h1>hello {{name}}</h1>
    `,
    setup(props, context) {
      const { watchEffect } = Vue;
      const { name } = props;
      watchEffect(() => {
        console.log(`name is: ` + name)
      })
    }
  });

  const vm = app.mount('#root');
</script>

</html>

运行结果

image-20210616113227270

使从props解构后的属性再次变成响应式

使用 toRefs 即可,参考”toRefs使解构对象的属性也变成响应式的“

子组件改变父组件传递过来的数据:改副本

我们在选项 API 里面写过一次了,这里再在组合式 API 里再写一次

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>hello vue</title>
  <!-- 引入Vue库 -->
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
  <div id="root"></div>
</body>

<script>

  const app = Vue.createApp({
    template: `
      <child :name="name" />
    `,
    setup(props, context) {
      const { ref } = Vue;
      const name = ref('zibo');
      return {
        name
      }
    }
  });

  app.component("child", {
    props: ['name'],
    template: `
      <h1>hello {{newName}}</h1>
      <input v-model="newName" />
    `,
    setup(props, context) {
      const { watchEffect, ref } = Vue;
      const newName = ref(props.name);
      watchEffect(() => {
        console.log(`name is: ` + newName.value)
      })
      return{ newName }
    }
  });

  const vm = app.mount('#root');
</script>

</html>

运行结果

image-20210616140138453

子组件改变父组件传递过来的数据:对外触发事件

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>hello vue</title>
  <!-- 引入Vue库 -->
  <script src="https://unpkg.com/vue@next"></script>
</head>

<body>
  <div id="root"></div>
</body>

<script>

  const app = Vue.createApp({
    template: `
      <child :num="num" @changeNum="handleChangeNum" />
    `,
    setup(props, context) {
      const { ref } = Vue;
      const num = ref(20);
      function handleChangeNum(parameter){
        num.value += parameter;
      }
      return {
        num, handleChangeNum
      }
    }
  });

  app.component("child", {
    emits:['changeNum'],
    props: ['num'],
    template: `
      <h1>hello {{num}}</h1>
      <button @click="changeNum">点我+5</button>
    `,
    setup(props, context) {
      const { watchEffect } = Vue;
      const { emit } = context;
      function changeNum(){
        emit('changeNum', 5);
      }
      watchEffect(() => {
        console.log(`num is: ` + props.num)
      })
      return{ changeNum }
    }
  });

  const vm = app.mount('#root');
</script>

</html>

运行结果

image-20210616142614283