从计算数据访问Vue Component道具

时间:2019-04-05 06:25:53

标签: vue.js

我在这里整理了一个最小的示例:https://codesandbox.io/s/vnyol7olp0?fontsize=14

src / MyComponent.vue 内部,我想从所声明的计算方法内部访问this.idx,但它抛出错误:

Cannot read property 'idx' of undefined

我无法弄清楚为什么this当时未定义,因为它可以在其他计算属性中使用。


main.js

import Vue from "vue";
import Vuex from "vuex";

// Import the `getField` getter and the `updateField`
// mutation function from the `vuex-map-fields` module.
import { getField, updateField } from "vuex-map-fields";

import App from "./App";

Vue.use(Vuex);
Vue.config.productionTip = false;

const store = new Vuex.Store({
  state: {
    user: {
      firstName: "",
      lastName: ""
    },
    addresses: [
      {
        town: ""
      }
    ]
  },
  getters: {
    getField
  },
  mutations: {
    updateField
  }
});

/* eslint-disable no-new */
new Vue({
  el: "#app",
  components: { App },
  store,
  template: "<App/>"
});

MyComponent.vue

<template>
  <div>
    <input v-model="firstName"> {{ firstName }}<br>
    <input v-model="lastName"> {{ lastName }}<br>
    <input v-model="town"> {{ town }}
  </div>
</template>

<script>
import { mapFields } from 'vuex-map-fields';

export default {
  name: 'MyComponent',
  props: ['idx'],
  computed: {
    // When using nested data structures, the string
    // after the last dot (e.g. `firstName`) is used
    // for defining the name of the computed property.
    ...mapFields([
      'user.firstName',
      'user.lastName',
      // It's also possible to access
      // nested properties in arrays.
      'addresses[' + this.idx + '].town',
    ]),
  },
};
</script>

index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>vuex-map-fields: Nested properties</title>
</head>

<body>
    <div id="app"></div>
</body>

</html>

2 个答案:

答案 0 :(得分:0)

如果您不坚持使用vuex-map-state模块,建议您使用getter function in high order function

高阶getter函数的主要思想是存储函数而不被调用,直到您在内部传递参数为止。我认为这将适合您将idx作为道具传递到MyComponent.vue。

此外,由于您正在使用v模型绑定值,因此需要添加setter and getter value in computed

// in store.js

const store = new Vuex.Store({
    // others state getter and mutations.
    getters: {
      getField,
      getStoreAddr(state) {
        return function(idx) {
          const defaultIdx = idx || 0;
          return state.addresses[defaultIdx].town;
        };
      }
    },
    mutations: {
      updateField,
      updateStoreAddr(state, { idx, town }) {
        const defaultIdx = idx || 0;
        state.addresses[defaultIdx].town = town;
      }
    }

})

// in MyComponent.vue script block

computed: {
    town: {
        // define getter and setter function to bind the value.
        get() {
            return this.$store.getters.getStoreAddr(this.idx)
        },
        set(town) {
            const idx = this.idx
            return this.$store.commit('updateStoreAddr', {idx, town})
        }
    }
}


完整的完整代码在这里: https://codesandbox.io/s/4x1qw7pmlw

希望我能解决您的问题!

答案 1 :(得分:0)

我的修复程序有些古怪,但是可以解决,它基于以下问题的答案:

Vue: How to use component prop inside mapFields

vuex-map-fields-prefixed.js

import datetime

x= input('opening time: ')
y= input('closing time: ')

t = datetime.time(8:30:0)

z= datetime.time(16:0:0)

def compute_opening_duration(t, z):

     if true
       return 7.5

    elif
     if false
       return 7.25

    else
      return -1

MyComponent.vue

export const mapFieldsPrefixed = function(prefix, fields) {
  return fields.reduce((prev, field) => {
    const fieldFunctions = {
      get() {
        const getterPath = 'getField';
        const pathPrefix = eval(prefix)
        const path = pathPrefix + field
        return this.$store.getters[getterPath](path);
      },
      set(value) {
        const mutationPath = 'updateField';
        const pathPrefix = eval(prefix)
        const path = pathPrefix + field
        this.$store.commit(mutationPath, { path, value });
      }
    };
    prev[field] = fieldFunctions;
    return prev;
  }, {});
}