VUEVue专题Vue技术

Vue3.0的setup学习笔记

2021-04-25  本文已影响0人  听书先生

1、setup的理解

setup组件选项在组件创建前执行,一旦props被解析,并充当Composition API的入口,也就是说组合API是在setup这个选项函数中使用的。

setup函数的注意点

2、setup函数的返回值

如果setup返回一个对象,会将对象合并到render context中去,此时就能够在组件template模板中使用该对象的属性。

<template>
  <div class="about">
    <h1>{{count}}</h1>
  </div>
</template>
<script>
export default {
  name:'About',
  setup(){
    // 组合api是在setup这个选项API中使用
    return {
      count: 10
    }
  }
}
</script>
image.png

3、返回渲染函数

setup中可以返回一个渲染函数,使用h去生成虚拟的DOM,Vue3.0支持直接return虚拟节点

注意:要从vue中引出来,否则h是未定义的状态

<template>
  <div class="about">
    <h1>{{count}}</h1>
  </div>
</template>
<script>
import {h} from 'vue'
export default {
  name:'About',
  setup(){
    return () => h('h1',{style:'color:red'},'这是createElement创建的DOM')
  }
}
</script>

image.png

4、setup接受的参数arguments

使用setup时,接受两个参数props和context(上下文),因为setup中不再有this了,因此props接受的值可以做为参数传过来,通过参数props去拿。

props参数

setup函数中的第一个参数是props,props是响应式的,当传入新的props,将会自动更新,因为在setup函数中,this并不是组件对象,因此无法向选项中通过this.prop去获取组件传递的数据,所以在setup函数中,将props通过参数的方式传递进来,同时,props是响应式的,当修改父组件中的count时,子组件的count会自动发生变化。
父组件

<template>
  <div class="home">    
    <children :count="count"/>
    <button @click="change">+1</button>
  </div>
</template>

<script>
import children from '../components/children'
import {ref} from 'vue'
export default {
  components:{
    children
  },
  setup(){
    const count = ref(0);
    const change = () => {
      return count.value++;
    }
    return {
      count,
      change,
    }
  }
}
</script>

子组件写法一

<template>
  <div>
    <h1>{{ count }}</h1>
  </div>
</template>

<script>
import {computed, toRefs} from 'vue';
export default{
  props:['count'],
  setup(props,{ emit }){
   let { count } = props;
    console.log(props.count)
   return {
     count
   }
  }
}
</script>

如果是这么直接解构去拿count的话,那么父组件修改了的count的值,子组件是不会跟着发生变化的,也可以理解为此时的count失去了活性。
那么有两种办法让子组件的数据激活,一种是toRefs()方法,另外一种是computed计算属性
方法一:toRefs(props)

<template>
  <div>
    <h1>{{ count }}</h1>
  </div>
</template>

<script>
import {computed, toRefs} from 'vue';
export default{
  props:['count'],
  setup(props,{ emit }){
   let { count } = toRefs(props);
    console.log(props.count)
   return {
     count
   }
  }
}
</script>
image.png
方法二:computed()计算属性
<template>
  <div>
    <h1>{{ count }}</h1>
  </div>
</template>

<script>
import {computed} from 'vue';
export default{
  props:['count'],
  setup(props,{ emit }){
   const count = computed({
     get:()=>props.count,
   })
   return {
     count
   }
  }
}
</script>
image.png

这样,父组件点击按钮加的值就会传给子组件,显示出来。

5、上下文context

setup函数接受的第二个参数是context,context是一个普通的javascript对象,他暴露出来的是三个组件的属性。

setup(props,context){
  console.log('打印context:',context)
  return{}
}
image.png

context 是一个普通的javascript对象,也就是说,他不是响应式的,因此,可以对其进行ES6进行解构使用。

export default {
    setup(props, { attrs, slots, emit }) {
        //...
    }
}

context对象中的attrs以及slots是具有状态的对象,非响应式的。

上一篇 下一篇

猜你喜欢

热点阅读