一.基本操作
第一步:安装Vuex
npm install --save vuex
第二步:配置Vuex文件,在src目录下新建一个store文件夹,文件夹下新建一个index.js,然后输入以下代码:
import {
createStore} from 'vuex'
//vuex的核心作用就是相当于一个管理所有组件之间状态(数据)的仓库
export default createStore({
state:{
counter:0
}
})
第三步:在主文件中引入Vuex,也就是在main.js文件中引入。
import {
createApp} from 'vue'
import App from './App.vue'
import store from './store' //引入vuex
createApp(App).use(store).mount('#app') //使用use()来绑定vuex的功能
第四步:在组件中读取状态
<template>
//第一种方式,直接通过$符来获取counter值
<p>counter:{
{
$store.state.counter}}</p>
//第二种方式,引入counter值
<p>{
{
counter}}</p>
</template>
<script>
//第二种方式,通过导入mapState来获取counter值
import {
mapState} from 'vuex'
export default{
name:'HelloWorld',
computed:{
...mapState(["counter"])
}
}
</script>
二.Vuex常用核心概念:State、Getter、Mutation、Action。
概念:
State:状态(数据)存储的地方。
Getter:对Vuex中的数据进行过滤。
Mutation:是更改Vuex中的状态(数据)的唯一方法。
Action:类似于Mutation,但不是直接更改状态,有异步操作的时候用Action。
2.这是store文件夹中的index.js,对基本操作中的代码进行扩展
import {
createStore} from 'vuex'
import axios from 'axios'
//这是store文件夹中的index.js,对基本操作中的代码进行扩展
export default createStore({
state:{
counter:0
},
//Getter:对Vuex中的数据进行过滤
getters:{
getCount(state){
return state.counter>0 ? state.counter : "coounter小于0,不符合要求"
}
},
//Mutation:是更改Vuex中的状态(数据)的唯一方法
mutations:{
setCounter(state,num){
state.counter +=num
}
},
//Action:类似于Mutation,但不是直接更改状态,有异步操作的时候用Action。
actions:{
//引用对象时,根据ES6的规则,要用{}包裹
asyncAddCounter({
commit}){
axios.get("http://iweniki.com/api/generator/list.php")
.then(res=>{
commit("setCounter",res.date[0])
})
}
}
})
3.在HelloWord.vue组件中的代码
<template>
//第一种方式,直接通过$符来获取counter值
<p>counter:{
{
$store.state.counter}}</p>
//第二种方式,引入counter值
<p>{
{
counter}}</p>
//================================
//引入getters对数据进行过滤
<p>counter={
{
$store.getters.getCounter}}</p>
//或
<p>counter={
{
getCounter}}</p>
//=================================
//使用matation来更改组件状态
<button @click="addClick">增加</button>
//=================================
//使用action异步网络请求
<button @click="addClick">增加</button>
</template>
<script>
//第二种方式,通过导入mapState来获取counter值
import {
mapState,mapGetters,mapActions} from 'vuex'
export default{
name:'HelloWorld',
computed:{
...mapState(["counter"]),
...mapGetters(["getCounter"])
},
methods:{
...mapMutations(["setCounter"]),
...mapActions(["asyncAddCounter"]),
addClick(){
//固定调用方式,"setCounter"表示index.js中的mutation里的setCounter()函数,
//15表示传过去的参数num
//这是调用mutation的其中一种方式
this.$store.commit("setCounter",15);
//另一种方式,先导入mapMutations,然后在methods里调用...mapMutations()
this.setCounter(15)
},
changeAsync(){
//acton的第一中调用方式
this.$store.dispatch("asyncAddCounter");
//第二种
this.asyncAddCounter();
}
}
}
</script>
Ok!完结