vuex的安装和使用方法
Vuex是一个状态管理工具,它可以协调Vue应用程序中组件状态的交互和逻辑。Vuex可以使得组件状态的共享变得容易,同时也可以使得代码逻辑更加清晰。
安装Vuex
安装Vuex很简单,只需要在终端中输入以下命令即可:
npm install vuex --save
如果还没有安装npm的话,请先安装npm。
然后把以下代码加到你的Vue实例中:
import Vuex from 'vuex'
Vue.use(Vuex)
//你的其他Vue代码...
代码解释:
首先,我们从Vuex库中导入Vuex对象。
然后,我们在Vue实例对象中注册了Vuex插件,这样就可以在整个Vue实例中使用Vuex了。
接下来,我们就需要创建Vuex的实例来管理数据了。
创建Vuex实例
当Vuex实例创建完成后,所有的组件都可以使用Vuex中的state、getter、mutation、action和modules等。以下是创建Vuex实例的代码:
const store = new Vuex.Store({
state: {
count:0
},
mutations: {
increment (state) {
state.count++
}
},
actions: {
incrementAsync ({ commit }) {
setTimeout(() => {
commit('increment')
}, 1000)
}
}
})
代码解释:
state:state对象包含了所有共享状态。这个状态是响应式的,当组件获取这个状态时,如果发生变化,那么相应的组件也会得到通知。在这里,我们创建一个名为count的属性。
mutation:mutation是更改状态的 方法。Vuex要求我们必须使用mutation来更改状态,因为这样可以方便地跟踪所有状态的变化。在这里,我们创建了一个名为increment的mutation,可以通过commit函数来调用这个mutation。
action:action与mutation很像,不同的是action提交的是mutation而不是直接更改状态。在这里,我们创建了一个名为incrementAsync的action,可以通过dispatch函数来调用这个action(注意:在Vue组件中调用这个action时需加上store.dispatch("incrementAsync"))
这样,就已经创建好了Vuex实例。接下来,我们就可以在Vue组件中使用Vuex的数据了。
使用Vuex
在Vue组件中,我们可以使用以下几个方式来使用Vuex:
读取state
以下代码演示了如何使用state:
<template>
<div>
<p>{{$store.state.count}}</p>
</div>
</template>
代码解释:
{{$store.state.count}}表示直接读取Vuex中的count数据。
注意:在Vue组件中,读取Vuex的数据时,可以省略$store,例如{{$store.state.count}}可以简化为{{state.count}}。
提交mutation
以下代码演示了如何提交mutation:
<template>
<div>
<button @click="$store.commit('increment')">+</button>
</div>
</template>
代码解释:
$store.commit('increment')表示提交increment这个mutation。
提交action
以下代码演示了如何提交action:
<template>
<div>
<button @click="$store.dispatch('incrementAsync')">+</button>
</div>
</template>
代码解释:
$store.dispatch('incrementAsync')表示提交incrementAsync这个action。
modules
如果你的应用程序很大,那么state的数据量也会很大。这时候,我们可以使用Vuex的模块化结构来提高代码的可维护性。
以下代码演示了如何使用modules:
const store = new Vuex.Store({
modules: {
user: {
state: {
token: null
},
mutations: {
setToken (state, token) {
state.token = token
}
},
actions: {
login ({ commit }) {
return new Promise((resolve, reject) => {
setTimeout(() => {
commit('setToken', 'tokenXXXXXXXXXXXXX')
resolve('登录成功')
}, 1000)
})
}
},
getters: {
getToken: state => state.token
}
}
}
})
代码解释:
通过modules选项来将Vuex的状态模块化。
在这个例子中,我们创建了一个名为user模块。
state:每个模块可以拥有自己的state对象,在这个例子中,user模块拥有自己的token属性。
mutation:同样也可以为每个模块创建mutation。
action:同样也可以为每个模块创建action。
getters:同样也可以为每个模块创建getter(Getter可以帮助我们从Vuex中的state中取值,并对取到的值进行加工处理)。
在Vue组件中使用模块:
<template>
<div>
<p>{{token}}</p>
<button @click="login">登录</button>
</div>
</template>
<script>
export default {
computed: {
token () {
return this.$store.getters['user/getToken']//指定user模块
}
},
methods: {
login () {
this.$store.dispatch('user/login')//指定user模块
}
}
}
</script>
代码解释:
this.$store.getters['user/getToken']:通过模块名/user和getter的名称getToken来获取state中的token属性。
this.$store.dispatch('user/login'):通过模块名/user,并且指定action名login,来调用用户登录的action。
这就是Vuex的基本用法,当然,Vuex还有更多复杂用法,在实际开发中会有更多的应用,这里只是入门教程。
