Vue button permission control

preface

In daily projects, it is necessary to determine the operation permission of the current user according to the data returned by the background interface. Must Display the delete button when you have delete permission. Without this permission, the button is not displayed or deleted. This is done through vuex by looking up information.

steps

1. Define the ButTom permission

Create buttomPermission in state to hold the permission data returned by the background interface.

SetPermission is used to receive data and pass page permission management into the buttomPermission object.

Use (vuex) const store = new vuex. store ({state: {buttomPermission: {}}, mutations: { setPermission(state, permission) { state.buttomPermission = permission } } }) export default storeCopy the code
2. Define the store
import store from './store/index.js'
​
new Vue({
    store,
    el: '#app',
    render: h => h(App)
})
Copy the code
3. Create apermissioninstruction

Create the directives folder and create the permission.js file.

The inserted function is used here, which checks whether the bound element has permissions when it is inserted into the parent node.

inserted( el, bindings, vnode ) { }
Copy the code
Use 4.permissioninstruction

Introduce and define permission directives in the button page, and write directives in butTom that bind values relative to directives.

<button v-permission="'add'"> Add </button>Copy the code
import permission from './directives/permission'
Copy the code
directives: {permission,},
Copy the code
5. Delete unauthorized data

In the Permission directive, get the value value of the button binding through the Bindings, then find it in the buttomPermission object, and determine whether there is a permission, if there is no permission, delete the node.

inserted(el, bindings, vnode) { let btnPermissionValue = bindings.value; let boolean =vnode.context.$store.state.buttomPermission[btnPermissionValue]; ! boolean && el.parentNode.removeChild(el); }Copy the code
6. Import status management data

Pass the state management data into the permission management through the setPermission method

let permissions = {}
this.$store.commit("setPermission", permissions);
Copy the code

General situation of

To sum up, you define a buttomPermission permission state object through vuex, and then create a Permissions directive by using the Permissions directive for each ButTom button and binding a value specific to that button. Then, in the permission.js file, get the current value and get whether the current button has permission from buttomPermission. If not, delete the current button node directly.

\