【问题标题】:Styled components - Trying to access json by a different key name样式化的组件 - 尝试通过不同的键名访问 json
【发布时间】:2020-03-30 03:13:28
【问题描述】:
import styled from "vue-styled-components";
const props = { type: String, action: Boolean };

const getter = () => {
  const permissionsList = JSON.parse(localStorage.getItem("UZ")).permissions;
  const type = props.type;
  const action = props.action;

  return permissionsList.type.action;
};

export const stylePermission = styled("span")`
  pointer-events: ${getter() ? "" : "none"};
  cursor: ${getter() ? "pointer" : "not-allowed"};
  opacity: ${getter() ? 1 : 0.4};
`;

我就是这样用的

<template slot="tab-head-roles">
   <sp-permission type="user" action="can_approve">
      <router-link to="/settings/roles">Roles</router-link>
   </sp-permission>
</template>

我无法访问return permissionsList.type.action;,因为JSON 对象中不存在type 和action,但对象中存在type 和action 的值。

什么是我访问它的最佳方式。

【问题讨论】:

  • 可能具有正确的属性名称?
  • 我不能使用正确的属性名称,因为它是动态的。
  • localStorage.getItem("UZ") 的价值是多少?
  • 在这种情况下,您永远无法知道您需要什么属性值。如果你的对象的结构每次都不一样,你就不会得到一致的结果
  • @stud3nt 我得到一个 json 对象

标签: javascript vue.js ecmascript-6 styled-components


【解决方案1】:

您可以使用方括号将type 和action 的值用作键名:-

const getter = () => {
  const permissionsList = JSON.parse(localStorage.getItem("UZ")).permissions;
  const type = props.type;
  const action = props.action;

  return permissionsList[type][action];
};

【讨论】:

  • 我试过这个。但我收到此错误Uncaught TypeError: Cannot read property 'function Boolean() { [native code] }' of undefined
  • 试试console.log(permissionsList[type][action]),看看你得到了什么价值。并且还可以显示权限列表示例?
【解决方案2】:

我就是这样解决的


import styled from "vue-styled-components";
const permissionProps = { type: String, action: String };

const getter = JSON.parse(localStorage.getItem("UZ")).permissions;

export const stylePermission = styled("span", permissionProps)`
  pointer-events: ${props => (getter[props.type][props.action] ? "" : "none")};
  cursor: ${props =>
    getter[props.type][props.action] ? "pointer" : "not-allowed"};
  opacity: ${props => (getter[props.type][props.action] ? 1 : 0.4)};
`;


【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-09-17
    • 1970-01-01
    • 2019-04-21
    • 2019-04-12
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多