16. vue3合成API,setup,reactive,toRef,toRefs,Ref,watchEffect,watch,project,inject

合成API 就是是相对应 选项API。 将相关联的数据和方法放置在一起编排。方便查看修改。
setup函数在创建组件之前执行,所以不能用this。
它跟data有点类似,都是有返回值,返回数据或者方法。

vue3中的 toRef Ref . toRef 是引用数据 Ref是复制数据
https://www.cnblogs.com/fsg6/p/14485509.html

示例一:与data写法非常类似

<template>
  <div>
    <h1 @click="changeEvent"> data计数:{{num}}</h1>
    <h1 > setup计数:{{count}}</h1>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";
import {ref} from "vue"
export default {
  name: "App",
  data() {
    return {
      num: 0,
    };
  },
  methods: {
    changeEvent: function () {
      this.num++;
    },
  },
  components: {},
  setup(){
    const count= ref(0)
    return {count}
  }
};
</script>

示例二:setup执行的时机

<template>
  <div>
    <h1 @click="changeEvent">data计数:{{ num }}</h1>
    <h1>setup计数:{{ count }}</h1>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";
import { ref } from "vue";
export default {
  name: "App",
  data() {
    console.log("data");
    return {
      num: 0,
    };
  },
  methods: {
    changeEvent: function () {
      this.num++;
    },
  },
  components: {},
  setup() {
    console.log("setup");
    const count = ref(0);
    return { count };
  },
  beforeCreate() {
    console.log("beforeCreate: 初始化数据之前");
  },
  created() {
    console.log("created: 数据初始化之后");
  },
  beforeMount() {
    console.log("beforeMount:挂载渲染之前");
  },
  mounted() {
    console.log("mounted: 挂载渲染之后");
  },
  beforeUpdate() {
    console.log("beforeUpdate: 更新之前");
  },
};
</script>

结果:在初始化数据之前

16. vue3合成API,setup,reactive,toRef,toRefs,Ref,watchEffect,watch,project,inject

示例三:setup中添加普通方法

<template>
  <div>
    <h1 @click="changeEvent">data计数:{{ num }}</h1>
    <h1 @click="changeCount">setup计数:{{ count }}</h1>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";
import { ref } from "vue";
export default {
  name: "App",
  data() {
    return {
      num: 0,
    };
  },
  methods: {
    changeEvent: function () {
      this.num++;
    },
  },
  components: {},
  setup() {
    const count = ref(0);
    function changeCount(){
      //setup当中取值需要加value,外面引用不需要
      count.value+=10
    }
    // 添加函数后,需要将其返回
    return { count,changeCount };
  },
};
</script>
<template>
  <div>
    <h1 >用户名::{{ username }}</h1>
    <h1 @click="changeType">{{ type }}</h1>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";
import { ref,reactive, toRefs } from "vue";
export default {
  name: "App",
  data() {
    return {
      num: 0,
    };
  },
  methods: {
    changeEvent: function () {
      this.num++;
    },
  },
  components: {},
  setup() {
    const count = ref(0);
    function changeCount(){
      //setup当中取值需要加value,外面引用不需要
      count.value+=10
    }

    const user = reactive({
      username:"老陈",
      age:30,
      type:"帅",
    })

    function changeType(){
      user.type="超级帅!"
    }

    // 添加函数后,需要将其返回
    return { count,changeCount,...toRefs(user),changeType };
  },
};
</script>

示例四: setup中reactive(响应式对象)

<template>
  <div>
    <h1 @click="changeEvent">data计数:{{ num }}</h1>
    <h1 @click="changeCount">setup计数:{{ count }}</h1>
    <h1 >用户名::{{ user.username }}</h1>
    <h1 >特点:{{ user.type }}</h1>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";
import { ref,reactive } from "vue";
export default {
  name: "App",
  data() {
    return {
      num: 0,
    };
  },
  methods: {
    changeEvent: function () {
      this.num++;
    },
  },
  components: {},
  setup() {
    const count = ref(0);
    function changeCount(){
      //setup当中取值需要加value,外面引用不需要
      count.value+=10
    }
    const user = reactive({
      username:"老陈",
      age:30,
      type:"帅",
    })
    // 添加函数后,需要将其返回
    return { count,changeCount,user };
  },
};
</script>

示例五: setup中toref/torefs 直接饮用属性

<template>
  <div>
    <h1 >用户名::{{ username }}</h1>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";
import { ref,reactive, toRefs } from "vue";
export default {
  name: "App",
  data() {
    return {
      num: 0,
    };
  },
  methods: {
    changeEvent: function () {
      this.num++;
    },
  },
  components: {},
  setup() {
    const count = ref(0);
    function changeCount(){
      //setup当中取值需要加value,外面引用不需要
      count.value+=10
    }
    const user = reactive({
      username:"老陈",
      age:30,
      type:"帅",
    })
    // 添加函数后,需要将其返回.因为user有很多属性,所以用toRefs,...表示解构
    return { count,changeCount,...toRefs(user) };
  },
};
</script>

示例六: setup中computed 调用对象内部的函数

<template>
  <div>
    <h1 >用户名::{{ username }}</h1>
    <h1 @click="changeType">{{ type }}</h1>
    <h1>{{ reverseType }}</h1>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";
import { ref,reactive, toRefs,computed } from "vue";
export default {
  name: "App",
  data() {
    return {
      num: 0,
    };
  },
  methods: {
    changeEvent: function () {
      this.num++;
    },
  },
  components: {},
  setup() {
    const count = ref(0);
    function changeCount(){
      //setup当中取值需要加value,外面引用不需要
      count.value+=10
    }

    const user = reactive({
      username:"老陈",
      age:30,
      type:"帅!",
      reverseType:computed(()=>{
        return user.type.split('').reverse().join('')
      })

    })

    function changeType(){
      user.type="超级帅!"
    }

    // 添加函数后,需要将其返回
    return { count,changeCount,...toRefs(user),changeType };
  },
};
</script>

示例七: setup中的watchEffect,watch 监听

<template>
  <div>
    <h1 >用户名::{{ username }}</h1>
    <h1 @click="changeType">{{ type }}</h1>
    <h1>{{ reverseType }}</h1>
  </div>
</template>

<script>
import HelloWorld from "./components/HelloWorld.vue";
import { ref,reactive, toRefs,computed,watchEffect } from "vue";
export default {
  name: "App",
  data() {
    return {
      num: 0,
    };
  },
  methods: {
    changeEvent: function () {
      this.num++;
    },
  },
  components: {},
  setup() {
    const count = ref(0);
    function changeCount(){
      //setup当中取值需要加value,外面引用不需要
      count.value+=10
    }

    const user = reactive({
      username:"老陈",
      age:30,
      type:"帅!",
      reverseType:computed(()=>{
        return user.type.split('').reverse().join('')
      })

    })

    function changeType(){
      user.type="超级帅!"
    }

    watchEffect(()=>{
      console.log(user.type)
      console.log('当usertype改变的时候,会触发此事件')
    })

    //单独监听
    watch(num,(newNum,preNum)=>{
      console.log(newNum,preNum)
    })
    //多个监听
    watch([num,user],(newNum,preNum)=>{
      console.log(newNum,preNum)
    })

    // 添加函数后,需要将其返回
    return { count,changeCount,...toRefs(user),changeType };
  },
};
</script>
<template>
<div>
  <h1 @click="changeEvent">计数:{{count}}h1>
  <h1 @click="changeNum">计数:{{num}}h1>

  <h1>用户名:{{user.username}}h1>
  <h1>用户名:{{user.type}}h1>

  <h1>用户名:{{username}}h1>
  <h1 @click="changeType"> 特点:{{type}}h1>
  <h1>特点翻转:{{reverseType}}h1>
div>
template>

<script>

import {ref,reactive,toRefs,computed,watchEffect,watch} from 'vue'
export default {
  name: 'App',
  data(){
    return {
      count:0
    }
  },
  methods:{
    changeEvent(){
        this.count++
    }

  },

  setup(){
    console.log("setup")

    const num=ref(0)

    const user = reactive({
      username:"老陈",
      age:30,
      type:"帅",

      reverseType:computed(()=>{
        return user.type.split('').reverse().join('')
      })
    })
    function changeType(){
      user.type="超级帅!"
    }

    function changeNum(){
      num.value+=10
    }

    watchEffect(()=>{
      console.log(user.type)
      console.log('当usertype改变的时候,会触发此事件')
    })

    watch(num,(newNum,preNum)=>{
      console.log(newNum,preNum)
    })

    watch([num,user],(newNum,preNum)=>{
      console.log(newNum,preNum)
    })
    return {num,changeNum,user,...toRefs(user),changeType}
  }
}
script>
<template>
    <div>
        <h1>username:{{username}}h1>
        <h1>age:{{age}}h1>
        <h1>description:{{description}}h1>
    div>
template>

<script>
import {ref,onBeforeMount,onMounted,onBeforeUpdate,onBeforeUnmount,onUnmounted} from 'vue'

export default {
    setup(props,content){
        console.log(props)
        console.log(content)
        const description = ref(props.username+"年龄是"+props.age)
        onBeforeMount(()=>{
            console.log("onBeforeMount")
        })
        onBeforeMount(()=>{
            console.log("onBeforeMount")
        })
        return {
            description
        }
    },
    props:[
        'username','age'
    ]
}
script>

示例八: 父向子传内容 props

子组件

<template>
    <div>
        <h1>username:{{username}}</h1>
        <h1>age:{{age}}</h1>
        <h1>description:{{description}}</h1>
    </div>
</template>

<script>
import {ref} from 'vue'
//content 获取父元素的内容
export default {
    setup(props){
        console.log(props)
        //props.username注意这儿只能用props 不能用this,因为setup函数 是在对象没生成前执行
        const description = ref(props.username+"年龄是"+props.age)
        return {
            description
        }
    },
    props:[
        'username','age'
    ]
}
</script>

父组件

<template>
  <div>
    <User :username="username" :age="age"/>
  </div>
</template>

<script>
import User from "./components/User.vue";
export default {
  name: "App",
  data() {
    return {
      username: "zhangsan",
      age:10
    };
  },
  methods: {
    changeEvent: function () {
      this.num++;
    },
  },
  components: {
    User
  },
};
</script>

示例九: contents

首先,setup(props,contents) 默认是包含这两个传递参数。contents就是上下文的意思。例如
子组件

<template>
    <div>
        <h1>username:{{username}}</h1>
        <h1>age:{{age}}</h1>
        <h1>description:{{description}}</h1>
    </div>
</template>

<script>
import {ref} from 'vue'
//content 获取父元素的内容
export default {
    setup(props,contents){
        console.log(contents)
        console.log(props)
        //props.username注意这儿只能用props 不能用this,因为setup函数 是在对象没生成前执行
        const description = ref(props.username+"年龄是"+props.age)
        return {
            description
        }
    },
    props:[
        'username','age'
    ]
}
</script>

父组件

<template>
  <div>
    // contents 可以获取到父元素的属性例如这个class
    <User :username="username" :age="age" class="abc" />
  </div>
</template>

<script>
import User from "./components/User.vue";
export default {
  name: "App",
  data() {
    return {
      username: "zhangsan",
      age:10
    };
  },
  methods: {
    changeEvent: function () {
      this.num++;
    },
  },
  components: {
    User
  },
};
</script>

16. vue3合成API,setup,reactive,toRef,toRefs,Ref,watchEffect,watch,project,inject

示例十: setup中生命周期函数

<template>
    <div>
        <h1>username:{{username}}</h1>
        <h1>age:{{age}}</h1>
        <h1>description:{{description}}</h1>
    </div>
</template>

<script>
import {ref,onBeforeMount,onMounted,onBeforeUpdate,onBeforeUnmount,onUnmounted} from 'vue'
//content 获取父元素的内容
export default {
    setup(props,content){
        console.log(props)
        console.log(content)
        const description = ref(props.username+"年龄是"+props.age)
        onBeforeMount(()=>{
            console.log("onBeforeMount")
        })
        onBeforeMount(()=>{
            console.log("onBeforeMount")
        })
        return {
            description
        }
    },
    props:[
        'username','age'
    ]
}
</script>

示例十一:project,inject

<template>
<div>
  <Student/>
</div>
</template>
<script>
// reactive : 用它创建一个响应对象,watchEffect 监听事件改变
// 通过provide函数 把对应的信息(学生信息)提供出去,然后需要用的组件通过注入inject的方式将数据得到
import {reactive,provide} from 'vue'
import Student from './components/Student.vue'
export default {
  name: 'App',
  data(){
    return {
    }
  },
  methods:{
  },
  components:{
    Student
  },
  // 合成 API  让数据和处理函数可以放在一起。 值是存储在num.value中
  setup(){
    // 通过provide函数 把自定义的信息提供供出去,provide:提供出去 inject: 注入进来
    const student = reactive({
      name:"小红",
      classname:"三年五班"
    })
    // 把student 通过stu1 传递出去
    provide('stu1',student)

    return {}
  }
}
</script>
<template>
    <div>
        <h1>学生</h1>
        <h1>name:{{name}}</h1>
        <h1>classname:{{classname}}</h1>
    </div>
</template>

<script>
import {inject} from 'vue'
//content 获取父元素的内容
//通过注入inject的方式将数据得到
export default {
    setup(props,content){
        const stu= inject('stu1')
        // ... 将对象解构出来
        return {...stu}
    }
}
</script>

Original: https://blog.csdn.net/wangzhicheng987/article/details/123556765
Author: 数哥
Title: 16. vue3合成API,setup,reactive,toRef,toRefs,Ref,watchEffect,watch,project,inject

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/733620/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球