vue非父子组件使用provide/inject传递函数

  1. 没有使用层层传递的方法
  2. 想要使用provide/inject的方式
  3. 网上查了都是传递数据,没看到有传递函数的
  4. 不知道能不能传递函数
  5. 希望牛掰的大lao解答解答,感谢了^^

爷爷组件

    const deleteTodo = (index:number) =>{
      state.todos.splice(index,1)
    }
    provide('deleteTodo',deleteTodo)

孙子组件

const deleteTodo = inject("deleteTodo")
    const delTodo = () =>{
      deleteTodo(props.index:Number)
    }

错误

img

定义el-dialog子窗口页面,不需要传递函数,子窗口可以通过$emit调用父窗口的方法。

可以的呀。。
官方有例子的。。其中的updateUserLocation就是传了函数过去。。。具体看:https://v3.vuejs.org/guide/composition-api-provide-inject.html#mutating-reactive-properties

父组件

<template>
  <MyMarker />
</template>

<script>
import { provide, reactive, ref } from 'vue'
import MyMarker from './MyMarker.vue'

export default {
  components: {
    MyMarker
  },
  setup() {
    const location = ref('North Pole')
    const geolocation = reactive({
      longitude: 90,
      latitude: 135
    })

    const updateLocation = () => {
      location.value = 'South Pole'
    }

    provide('location', location)
    provide('geolocation', geolocation)
    provide('updateLocation', updateLocation)
  }
}
</script>

子组件:

<!-- src/components/MyMarker.vue -->
<script>
import { inject } from 'vue'

export default {
  setup() {
    const userLocation = inject('location', 'The Universe')
    const userGeolocation = inject('geolocation')
    const updateUserLocation = inject('updateLocation')

    return {
      userLocation,
      userGeolocation,
      updateUserLocation
    }
  }
}
</script>