使用Vue验证内容密钥Json是否存在

时间:2017-10-12 14:12:22

标签: javascript vue.js

我想知道如何检查" novalue"存在 例如:

{
    name: "maria",
    city_id: "novalue"
    ....
}

我如何在Vue中这样做? 在<div v-if="condition">或函数中执行吗?

1 个答案:

答案 0 :(得分:3)

如果您想/可以使用ES7功能:

const containsKey = (obj, key ) => Object.keys(obj).includes(key);

实施例:

const someCoolObject = {name: 'Foo', lastName: 'Bar'};

const hasName = containsKey(someCoolObject, 'name');
const hasNickName = containsKey(someCoolObject, 'hasNickName');

console.log(hasName, hasNickName); // true, false

对于Vue:

组件:

{
    methods: {
        containsKey(obj, key ) {
            return Object.keys(obj).includes(key);
        }
    },
    computed: {
        hasName() {
            return this.containsKey(this.someObject, 'name');
        }
    }
}

模板:

<div v-if="hasName"></div>