[Vuejs]-Upgrade component from option api to composition api (this.$parent)

0👍

You can get the parent from the instance using the getCurrentInstance() method

Then to access data you could use instance.parent.data, but that won’t work, because your data is not defined there. Vue makes the data passed to the view available still through instance.parent.proxy, so you can access the Proxia via instance.parent.proxy.tabs

And while his should work accessing data of the parent this way is highly discouraged. You may want to consider passing props directly (if it’s a parent-child relationship), or you could use the provide/inject way of doing it, or if the parent is used only once, then a global store may work as-well. Doing it using parent.proxy.* relies on internals that may cause a braking change at some point.

Example also includes passing with provide/inject

var app = Vue.createApp({
  setup() {

    const tabs = Vue.ref([1])
    Vue.provide('tabs', tabs)

    const selectedTab = (selectedTab) => {
      tabs.value.forEach(tab => {
        tab.isActive = (tab.name === selectedTab.name);
      })
    }

    return {
      tabs,
      selectedTab
    }
  }
});

app.component("child-component", {
  template: `<div >🧒<button @click="gift">🎁</button></div>`,
  setup() {
    const instance = Vue.getCurrentInstance();
    const tabs = Vue.inject('tabs')
    const gift = ()=>{
      instance.parent.proxy.tabs.push('🌼'); // using proxy
      tabs.value.push('🌻'); // using inject
    }
    Vue.onBeforeMount(() => {
      gift();
    })

    return {gift}
  }
});

app.mount("#app");
<script src="https://unpkg.com/vue@3.0.6/dist/vue.global.prod.js"></script>
<div id="app">
👩‍🦰
  {{tabs}}
  <child-component></child-component>
  <child-component></child-component>
</div>

Leave a comment