vue3的setup使用

vue3的setup使用

setup的设计是为了使用组合式apisetup位于created 和beforeCreated之前,用于代替created 和beforeCreated,但是在setup函数里不能访问到this,另外setup内可以通过以下hook操作整个生命周期onBeforeMount,onMounted,onBeforeUpdate,onUpdated,onBeforeUnmount,onUnmounted,onErrorCaptured,onRenderTracked,onRenderTriggered

1. setup可以接收哪些参数?

使用 setup 函数时,它将接收两个参数:props,context

export default {
	props:{
		title: String
	},
	setup(props, ctx) {
		//setup 函数中的 props 是响应式的,当传入新的 prop 时,它将被更新。
		console.log(props.title)
		
		// Attribute (非响应式对象,等同于 $attrs)
	    console.log(context.attrs)
	
	    // 插槽 (非响应式对象,等同于 $slots)
	    console.log(context.slots)
	
	    // 触发事件 (方法,等同于 $emit)
	    console.log(context.emit)
	
	    // 暴露公共 property (函数)
	    console.log(context.expose)
	}
}
2. 在 setup() 内部,this 不是该活跃实例的引用

getCurrentInstance 获取当前组件的实例、上下文来操作router和vuex等。 (请不要把它当作在组合式 API 中获取 this 的替代方案来使用)

import { getCurrentInstance } from 'vue';
export default {
	setup() {
		console.log(this) // undefined
		
		const instance = getCurrentInstance();
		// 获取当前组件的上下文,下面两种方式都能获取到组件的上下文。
		const { ctx }  = getCurrentInstance();  //  方式一,这种方式只能在开发环境下使用,生产环境下的ctx将访问不到
		const { proxy }  = getCurrentInstance();  //  方式二,此方法在开发环境以及生产环境下都能放到组件上下文对象(推荐)
		// ctx 中包含了组件中由ref和reactive创建的响应式数据对象,以及以下对象及方法;
		proxy.$attrs
		proxy.$data
		proxy.$el
		proxy.$emit
		proxy.$forceUpdate
		proxy.$nextTick
		proxy.$options
		proxy.$parent
		proxy.$props
		proxy.$refs
		proxy.$root
		proxy.$slots
		proxy.$watch
	}
}
3. 在setup中通过ref获取dom
<template>
	<div ref="openLayer"></div>
</template>
import {ref,onMounted} from 'vue';
<script>
export default{
  setup(){
    let openLayer= ref(null);// 创建一个响应式数据,并且要把响应式数据暴露出去 
    onMounted(()=>{
      console.log(openLayer.value) // 当元素被创建出来的适合,就会给对应的响应数据赋值
    });
    return {openLayer}
  }
}
</script>
4. 在setup中使用eventbus

我们可以使用第三方库Vue3-Eventbus或者动手写一个也行

// bus.js
export default class EventBus{
    constructor(){
        this.events = {};
    }
    emit(eventName, data) {
        if (this.events[eventName]) {
            this.events[eventName].forEach(function(fn) {
                fn(data);
            });
        }
    }
    on(eventName, fn) {
        this.events[eventName] = this.events[eventName] || [];
        this.events[eventName].push(fn);
    }

    off(eventName, fn) {
        if (this.events[eventName]) {
            for (var i = 0; i < this.events[eventName].length; i++) {
                if (this.events[eventName][i] === fn) {
                    this.events[eventName].splice(i, 1);
                    break;
                }
            };
        }
    }
}

在main.js中挂载

// main.js
import { createApp } from 'vue'
const app = createApp(App)
import EventBus from '@/bus.js'
const bus = new EventBus()
// 1.使用provide注入
app.provide('$bus', bus)
// 2.挂载到this上
app.config.globalProperties.$bus = bus

在setup中使用

import { inject } from 'vue'
export default {
  setup() {
      const $bus = inject('$bus')
      $bus.emit('handler')
  },
  created() {
      this.$bus.emit('handler')
  }
}
5. 在setup中使用vuex

访问 State Getter Mutation Action

import { computed } from 'vue'
import { useStore } from 'vuex'

export default {
  setup () {
    const store = useStore()

    return {
      // 在 computed 函数中访问 state
      count: computed(() => store.state.count),

      // 在 computed 函数中访问 getter
      double: computed(() => store.getters.double)
	
	 // 使用 mutation
      increment: () => store.commit('increment'),

      // 使用 action
      asyncIncrement: () => store.dispatch('asyncIncrement')
    }
  }
}
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue3中,可以使用`setup`函数来定义组件。`setup`函数接收两个参数,`props`和`context`。`props`是父组件传递的属性,而`context`包含了一些常用的属性,如`attrs`、`slots`和`emit`。 在`setup`函数中,你可以使用Vue的Composition API来定义组件逻辑。你可以使用`ref`或`reactive`来定义响应式数据,使用`computed`来定义计算属性,以及使用`watch`来监听数据的变化。 例如,你可以在`setup`函数中返回一个对象,该对象中包含了组件的响应式数据和方法。这样,组件就可以使用这些数据和方法了。 以下是一个示例代码: ```javascript const app = Vue.createApp({ setup() { const count = ref(0); // 定义一个响应式数据 function increment() { count.value++; // 修改响应式数据 } return { count, // 将响应式数据暴露给组件 increment // 将方法暴露给组件 }; } }); app.mount('#app'); ``` 在上面的代码中,我们使用`ref`来定义了一个响应式数据`count`,并定义了一个方法`increment`来修改该数据。最后,我们将`count`和`increment`返回给组件使用。 通过使用`setup`函数,我们可以更灵活地组织组件的逻辑,并且更好地组织和重用代码。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [vue3 setup使用](https://blog.csdn.net/weixin_43876728/article/details/119142725)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值