使用 Vue 3 提供带有设置功能的注入

有人知道如何提供设置函数中的变量吗?


export default {

  name: "MyComponent",

  provide: {

    myVariableThatIWantToProvide // This is not working

  },

  setup() {

    const myVariableThatIWantToProvide = ref('test');


    return {

      myVariableThatIWantToProvide

    };

  }

};

</script>


holdtom
浏览 105回答 1
1回答

米琪卡哇伊

您应该从 vue 导入provide并在 setup 函数中使用:import {ref,provide} from "vue"export default {&nbsp; name: "MyComponent",&nbsp;&nbsp; setup() {&nbsp; &nbsp; const myVariableThatIWantToProvide = ref('test');&nbsp; &nbsp; &nbsp; provide ('myVariableThatIWantToProvide', myVariableThatIWantToProvide )&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; myVariableThatIWantToProvide&nbsp; &nbsp; };&nbsp; }};</script>在孙子组件中:import {inject} from "vue"export default {&nbsp; name: "somechild",&nbsp;&nbsp; setup() {&nbsp; &nbsp; &nbsp; const myVariableThatIWantToProvide =inject ('myVariableThatIWantToProvide')&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; myVariableThatIWantToProvide&nbsp; &nbsp; };&nbsp; }};</script>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript