【问题标题】:Vue: Property or method is not defined on the instanceVue:实例上未定义属性或方法
【发布时间】:2021-07-17 02:28:17
【问题描述】:

我有 2 个组件(Q1 和 RepConfig)。我正在尝试在 RepConfig 中导入 Q1 组件,以便我可以一遍又一遍地使用它。 Q1 组件指向一个带有简单数组的 Vue 存储 (dscpValues.js):

export default {
    namespaced: true,
    state: {
        dscpData: [
            { id: 'cs0', value: 'CS0' },
            { id: 'cs1', value: 'CS1' },
            { id: 'cs2', value: 'CS2' },
            { id: 'cs3', value: 'CS3' },
            { id: 'cs4', value: 'CS4' },
            { id: 'cs5', value: 'CS5' },
            { id: 'cs6', value: 'CS6' },
            { id: 'cs7', value: 'CS7' }
        ]
    }
};

Q1 组件:

<template>
    <div>
        <ul v-for="(option, index) in dscpValues.dscpData" :key="index">
            <li>
                <input type="checkbox" class="inputMarginRight" :id="option.id" :value="option.value" v-model="dscpChoiceQ1" />
                <label for="id">{{ option.value }}</label>
            </li>
        </ul>
    </div>
</template>

<script>
import { mapState } from 'vuex';
import { ref, computed } from '@vue/composition-api';

export default {
    computed: {
        ...mapState(['dscpValues'])
    },
    setup() {
        const dscpChoiceQ1 = ref([]);
        const dscpValuesQ1 = computed({
            get: () => {
                const v = dscpChoiceQ1.value;

                return v.join(' ');
            },
            set: (newval) => {
                dscpChoiceQ1.value = newval;
            }
        });

        return {
            dscpChoiceQ1,
            dscpValuesQ1
        };
    }
};
</script>

RepConfig 组件:

<template>
    <div>
        <queue-one></queue-one>
    </div>
    <span>{{ dscpValuesQ1 }}</span>
</template>

<script>
import QueueOne from './QueueNumber/Q1';

export default {
    components: {
        QueueOne
    }
}
</script>

我得到“方法或属性 dscpValuesQ1 未在实例上定义,但在渲染期间被引用”。我做错了什么?

【问题讨论】:

  • &lt;span&gt;{{ dscpValuesQ1 }}&lt;/span&gt;dscpValuesQ1undefinedRepConfig Component
  • 是的,我如何指向导入组件的dscpValuesQ1
  • 您可以使用scoped-slot 将数据从Child 传递给Parent。

标签: vue.js


【解决方案1】:

当它似乎存储在子 QueueOne (Q1) 组件(指向 VueX 存储)中时,您正尝试访问 RepConfig 组件中的值 dscpValuesQ1。默认情况下,父组件无权访问其子组件的数据。

您可以通过向父组件添加相同的 VueX 连接并以这种方式获取值来访问数据,或者通过在父组件的模板中为子组件添加 ref,并在父组件上监视更改在您的子组件上 (as answered here)。例如:

<template>
    <div>
        <queue-one ref="q1"></queue-one>
    </div>
    <span>{{ dscpValuesQ1 }}</span>
</template>

<script>
import QueueOne from './QueueNumber/Q1';

export default {
    components: {
        QueueOne
    },

    mounted() {
        this.$watch("$refs.q1.dscpValuesQ1", (new_value, old_value) => {
            // Store data in this (parent) component
        }
    }
}
</script>

【讨论】:

  • 这是有道理的,但我仍然收到dscpValuesQ1 undefined ...
  • 你能发布一个 JSFiddle 吗?我猜您收到错误是因为您在尝试使用它之前没有检查变量是否存在。也许在您尝试使用该变量的元素上添加一个 v-if?
猜你喜欢
  • 1970-01-01
  • 2020-07-14
  • 2017-08-28
  • 2019-04-08
  • 2019-08-30
  • 2018-09-05
  • 2019-01-21
  • 2018-07-24
  • 2021-05-04
相关资源
最近更新 更多