vuex的使用
vuex概念
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式
vue安装
npm install vuex --save
yarn add vuex
配置
1.在src下新建一个store文件夹,文件夹里新建store.js
2.在index.js里引入vue、vuex
import Vue from 'vue';
import Vuex from 'vuex'
//使用
Vue.use(Vuex)
3.在main.js里引入vuex文件
import { store} from './store/store'
new Vue({
store:store, //使用store
el: '#app',
router,
components: { App },
template: '<App/>',
})
什么情况下使用vuex
如果需要构建一个中大型单页应用,则会需要更好的组件外部管理状态,这时最好使用vuex
vuex基本组成
- state:用于存储数据,类似vue实例的data属性。
store.js中
//创建且声明一个对象
export const store = new Vuex.Store({
state:{
isShow:true,
items:[
{
name:"张三",
num:"1"
},
{
name:"李四",
num:"2"
},
{
name:"王五",
num:"3"
}
]
}
})
外部组件中调取数据:
computed:{
itemList(){
return this.$store.state.items
}
},
//这里有两种办法
//p在computed的itemList方法中循环
<p v-for="item in itemList">{ { item.num}}{ { item.name}}</p>
//p直接指向store中的state的items数组
<p v-for="item in this.$store.state.items">{ { item.num}}{ { item.name}}</p>
getters:用来获取state里的属性值),在实例里用 this.store.state.属性名 来获取值
store.jsgetters:{
numChange(state){
return state.items.forEach(item=>{
item.num+=100
})
}
}
组件中:
//写法一:
<p v-for="item in this.$store.getters.numChange">{ { item.num}}{ { item.name}}</p>
//写法二:
<button @click="numTurn">改变数字</button>
computed:{
numChange(){
return this.$store.getters.numChange
}
},
mutations:用于递交更改,对state对象中的属性数据进行更改。
可以使用mutations配合vuex提供的commit方法来修改state中的状态
store.jsexport const store = new Vuex.Store({
state:{isShow:false,
myData:'',
items:[
{
name:"张三",
num:1
},
{
name:"李四",
num:2
},
{
name:"王五",
num:3
}
]
},
mutations:{//定义一个函数动态修改state的状态值
numTurn(state){ /这里的state代表上面的State
state.items.forEach(item=>{
item.num+=100
})
}
}
})
组件中
//写法一:
<button @click="$store.commit('numTurn')">改变数字</button>
//写法二:
<button @click="numTurn">改变数字</button>
methods:{
numTurn(){
this.$store.commit('numTurn')
}
}
- actions(类似于Mutations):用于进行递交异步更改,通过调用mutations实现对数据的更改。
- module:将 store 分割成模块(当东西存放太多的时候,可以考虑进行拆分)
actions与mutations的区别:
Aciton提交的是mutation,而不是直接变更状态
Action可以包含任何异步操作
还没有评论,来说两句吧...