请求后Vue变量值未更新

时间:2019-03-15 07:52:50

标签: javascript html vue.js vuejs2 frontend

大家好,我在变量值方面遇到麻烦。

在请求中,如果每个数组值都是匹配的,我就将它们匹配,然后将 match 变量更新为true。问题在于返回的 match 变量在请求内部进行更新后,并未在请求外部进行更新。如何获得更新的匹配值?

模板

<template>
   <div>{{$acl(['post.edit'])}}</div> <!-- always display false -->
</template>

Nuxt插件

let match = false
let moduleName = ''
let actionName = ''

Vue.prototype.$acl = ( access ) => {

    let bindAccess = access

    storeRequest.then( done => {
        _.each( bindAccess, ( value, index ) => {
            moduleName = value.split('.')[0]
            actionName = value.split('.')[1]

            /**
             * check if user access modules match with bindAccess module
             */
            if( aclConfig[moduleName] != undefined ) {
                _.each( aclConfig[moduleName], ( actions, index ) => {
                    if(actions.action_name === actionName) {
                        match = true
                        return false
                    }
                })
            }
        })

        console.log(match) //returns true since their is a match
    })

    console.log(match) //always returns false
    return match
}

2 个答案:

答案 0 :(得分:1)

在方法返回后,解决了诺言,因此在方法返回后更改match,因此您总是会得到错误的结果。

您应该在组件实例上声明一个字段,然后从插件内部更改该变量。

<template>
 <div>{{$acl(['post.edit']), isAMatch}}</div>
</template>

并在插件中

Vue.prototype.$acl = ( access ) => {

 let bindAccess = access

 storeRequest.then( done => {
    _.each( bindAccess, ( value, index ) => {
        moduleName = value.split('.')[0]
        actionName = value.split('.')[1]

        /**
         * check if user access modules match with bindAccess module
         */
        if( aclConfig[moduleName] != undefined ) {
            _.each( aclConfig[moduleName], ( actions, index ) => {
                if(actions.action_name === actionName) {
                    this.isAMatch = true
                    return false
                }
            })
        }
    })
 })

 // no need to return here
 // return match
}

答案 1 :(得分:0)

您必须使用mixins,如下所示:

{
  data: () => {
    return { 
       aclConfig
    }
  },
  created() {
    this.aclConfig = this.$store.getAclConfig(); // or maybe using Promise
  },
  methods: {
    checkAccess(roles) {
       let match = false;
       _.each(roles, (role) => {
         const splited = value.split('.');
         const moduleName = splited[0];
         const actionName = splited[1];
         if (this.aclConfig[moduleName]) {
            _.each(this.aclConfig[moduleName], (actions) => {
              if (actions.action_name === actionName) {
                match = true;
                return false;
              }
           });
        }
      });

      return match;
    }
  }
}

您可以像这样在模板中使用它:

<template>
 <div>{{ checkAccess(['post.edit']) }}</div>
</template>