When using vuex to manage component status, it is a bit confusing where to use data, method, and where to use state, mutation, and actions
漂亮男人2017-05-19 10:46:31
vuex In fact, in simple terms, it is a global namespace. That is a global variable. Then the actions and states linked to vuex are available globally.
Generally when we write components (actually business components, functional components rarely use vuex), we need to figure out whether the current business component has methods or data that needs to be passed to its TA component?
For example:
There is such a scene. Assume that there is a management system with a public login module and a business module that jumps after login.
Then the definition of the login module will be like this.
// 登陆模块
const state = {
user: { } // 存储用户信息
}
const action = {
login() { ... } // 调用API登陆
}
const mutation = {
setLogin(state, user){
state.user = user
}
}
Defined in this way, login(),user can be called wherever you want to call it.
If it is this kind of method, we should define it in vuex.
On the contrary, if your attribute is only for use inside the current component, for example:
<p v-if="isShow">
show...
</p>
<button @click="toggle">切换</button>
export default{
data(){
return { isShow: false }
},
method: {
toggle(){
this.isShow = !this.isShow
}
}
}