【问题标题】:Vue 2 with Composition API ReactiveVue 2 与 Composition API 反应式
【发布时间】:2022-10-19 18:31:12
【问题描述】:

对于遗留项目,我们需要使用 vue 2。 但是我们想通过使用 @vue/composition-api 来实现状态 Vue 2

但我唯一的问题是,如何将它与 options api 一起使用?

我有一个带有.js 文件的概念证明

    import { reactive } from '@vue/composition-api';

    const state = reactive({
        counter : 0
    })

    export default{ state }

设置很简单:

    <template>
        <h1>hi
            <div>We still in it: {{ counter }}</div>
            <button @click="increment">+</button>
        </h1>
    </template>
    
    <script>
    import { defineComponent, computed } from '@vue/composition-api'
    
    export default defineComponent({
        name: "TestStateHello",
        setup() {
            const store = require("./useState").default;
    
            return {
                counter: computed(() => store.state.counter),
                increment: () => store.state.counter++,
            };
        },
    })
    </script>

但是当我想使用常规选项 api 来访问计数器的反应状态时,我似乎不知道如何。

您的帮助将不胜感激!

【问题讨论】:

    标签: vuejs2 vue-composition-api


    【解决方案1】:

    只需全局导入它(在返回的选项对象之外):

    <template>
        <h1>hi
            <div>We still in it: {{ counter }}</div>
            <button @click="increment">+</button>
        </h1>
    </template>
    
    <script>
    import { defineComponent, computed } from '@vue/composition-api'
    // Alternative (after fixing export): import {store} from './useState';
    // You can use this in setup, too - no need to the require inside the setup()
    const store = require("./useState").default;
    
    export default defineComponent({
        name: "TestStateHello",
        computed: {
            counter: () => store.state.counter,
        },
        methods: {
            increment: () => store.state.counter++,
        }
    })
    </script>
    
    

    我建议您将导出更改为:

    import { reactive } from '@vue/composition-api';
    
    const state = reactive({
        counter : 0
    })
    
    export state; // < then import works as above
    

    【讨论】:

    • 谢谢!这似乎是显而易见的解决方案
    【解决方案2】:

    在处理options api 时,您可以使用provide-inject-concept

    这个怎么运作。

    您可以在 main.js 中 provide 存储文件,如下所示

    import GStore from "./useState"
    app.provide('GStore',GStore)
    

    然后在组件中你可以inject那个商店

    export default {
      inject:["GStore"]
      methods:{
    
         //Code just to show how to access store counter
         testingState(){
            return this.GStore.state.counter;
         }
      }
    }
    

    【讨论】:

    • 好的旁注!如果这仍然适用于 SSR,我将尝试
    猜你喜欢
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 2021-06-23
    • 2021-03-05
    • 2021-01-08
    相关资源
    最近更新 更多