javascript pinia中的动态吸气剂- Vue 3

snz8szmq  于 2023-05-16  发布在  Java
关注(0)|答案(1)|浏览(117)

Vue 2 with Vuex 3.4代码:

getLink: (state, getters) => rel => {
  let link = state.data?.getLinkWithRel(rel);
  let stac = getters[rel];
  let title = STAC.getDisplayTitle([stac, link]);
  if (link) {
    link = Object.assign({}, link);
    link.title = title;
  }
  else if (stac instanceof STAC) {
    return {
      href: stac.getAbsoluteUrl(),
      title,
      rel
    };
  }
  return link;
},

这段代码应该移植到Vue 3 with pinia。执行以下操作:

getLink: (state) => (rel) => {
  let link = state.data?.getLinkWithRel(rel);
  let stac = state[rel];
  let title = STAC.getDisplayTitle([stac, link]);

  if (link) {
    link = { ...link };
    link.title = title;
  }
  else if (stac instanceof STAC) {
    return {
      href: stac.getAbsoluteUrl(),
      title,
      rel
    };
  }

  return link;
},

stac变量包含nullundefined值。
使用版本1时,stac包含被调用的getters[rel]函数返回的数据。

如何写入或强制pinia给予数据?

其他信息:
rel-包含一个getter名称(parentcollection)的字符串。
getter-parent:

parent: (state) => state.getStacFromLink('parent'),

其中getStacFromLink也是一个getter。
getter-collection:

collection: (state) => state.getStacFromLink('collection'),

看起来被调用的parentcollection getter没有获取Store的状态。

cyej8jka

cyej8jka1#

你的解决办法对我来说似乎有点太复杂了。
如果两个getter函数parentcollection都只是用硬编码的rel调用getStacFromLink,那么为什么不简单地

let stac = state.getStacFromLink(rel);

我还没有找到一种在Pinia中动态访问getter的方法。我觉得这样很好。考虑过度考虑你的getter和商店设计。

const { createApp, ref } = Vue
const { createPinia, defineStore, storeToRefs } = Pinia

const Store = defineStore('test',
{
    state: () => {
      return { data: 
        {
          getLinkWithRel: (rel) => {
             return { href: rel, title: rel }
          }
        }
      }
    },
    getters: {
      parent: (state) => state.getStacFromLink('parent'),
      getStacFromLink: (state) => (rel) => {
        return { stac: rel }
      },      
      getLink: (state, getters) => (rel) => {
        let link = state.data?.getLinkWithRel(rel);
        console.log(link);
        let stac = state.getStacFromLink(rel);
        console.log(stac);             
        return link;
      }
    }
  }
)

const App = {
  setup() {
    const store = Store()
    const refs = storeToRefs(store)
    return {
      store, refs
    }
  }
}

const app = createApp(App)
const pinia = createPinia()
app.use(pinia)
app.mount('#app')
#app { line-height: 1.75; }
[v-cloak] { display: none; }
<div id="app">
getLink('parent'):  {{ store.getLink('parent') }}<br/>
getLink('collection'):  {{ store.getLink('collection') }}<br/>
refs['parent']: {{ refs['parent'] }}
</div>
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<script src="https://unpkg.com/vue-demi@0.13.11/lib/index.iife.js"></script>
<script src="https://unpkg.com/pinia@2.0.30/dist/pinia.iife.js"></script>

相关问题