vue3 Composition-API
  • 获取组件实例

    在options api里面使用this来获取实例

    在setup里this指向window的,我们可以通过 getCurrentInstance()这个接口来获取组件实例

    setup() {
      // getCurrentInstance()可以获取组件实例
      const instance = getCurrentInstance()
      console.log(instance);
      onMounted(()=>{
        // 组件实例的上下文是我们熟悉的this
        console.log(instance.ctx.foo); // 'foo'
        console.log(instance.ctx.bar()); // '我是bar方法'
      })
      return {}
    }
    
    vue3中组件实例结构,各个选项中的this实际上是ctx或proxy
    但ctx并非一个Proxy对象,若是想要利用响应也行,还是得用proxy属性来返回上下文对象的。
    
  • 派发自定义事件

    之前派发自定义事件,通过this.$emit()派发事件。现在我们可以通过以下方式来实现:

    • setup(props, ctx) {
        getCurrentInstance().emit('ooxx') 
        ctx.emit('ooxx') 
      }
      还可以把emit直接解构出来使用
      setup(props, { emit }) {
      	emit('ooxx')
      }
      
  • composition-api引入了独立的数据响应式方法reactive,可以将传入的对象做响应式处理

    const state = reactive({
      foo: 'foo',
    })
    watchEffect(() => {
      console.log(state.foo)
    })
    state.foo = '你好' // 输出 '你好'
    

    以上的方式有些像我们之前设置的data选项,但是当我们导出state值时就要带上这个前缀,此时我们可以引入toRefs,将reactive()返回代理的每一key对应的值都转换为Ref,Ref通过包装单值为Ref对象,以此来做响应式代理,但使用Ref对象的时候,需要在这个值上加上value才可以获取到。

    setup() {
    	const state = reactive({})
    	return { ...toRefs(state) }
    }
    
  • watch和watchEffct

    这两个都是观察响应式数据,变化执行副作用函数的,但也有不同。

    • watch需要明确指定监视目标

    • watch(() => state.counter, (val, prevVal) => {})
      
    • watchEffct就不需要

    • watchEffect(() => {
      	console.log(state.counter)
      })
      
    • watch可以获取变化前后的值,是懒执行的,等效于this.$wacth(),wacthEffct是为了收集依赖,要立即执行一次。

Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐