- Vuex 是什么?
Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。 -
vuex的六种方法
state的使用方法及场景
-
state的使用场景及方法
- 第一种方法:在元素中使用
<p>{{$store.state.name}}</p>
this.$store.state.name
<p>{{name}}</p>
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState([
'name',
]),
},
</script>
mutations 的使用方法及场景
| 方法 | 作用 |
|---|
| mutations | vuex改变vuex的唯一途径,事件方法 |
- 需要先在vuex的methods中传递事件,然后在vuex中接收事件使用,这种触发函数并携带参数的方法叫做载荷。
- 传递方法给vuex
this.$store.commit('changeTel', 110)
- vuex接收事件
- mutations接收的事件有一个固定形参state,他代表state方法,第二个参数是传递过来的数据
mutations: {
changeTel(state, val) {
console.log(val)
},
},
<script>
import { mapMutations } from 'vuex'
export default {
methods:{
...mapMutations([
'changeTel',
]),
exitUser() {
this.changeTel({tel: 110, age: 18})
},
}
</script>
actions 的使用方法及场景
actions: {
changeAsync() {
return new Promise((resolve) => {
setTimeout(() => {
var list = [{
name: "商品一",
price: 100
},
{
name: "商品二",
price: 1200
}]
resolve(list)
}, 1000);
})
}
},
created() {
this.$store.dispatch('changeAsync', '123').then(res => {
this.changeShopList(res)
})
},
<script>
import { mapActions } from 'vuex'
export default {
created() {
this.changeAsync().then(res => {
this.changeShopList(res)
})
},
methods:{
...mapActions([
'changeAsync',
]),
},
</script>
getters 的使用方法及场景
| 方法 | 作用 |
|---|
| getters | 计算属性,相当于vue中的computed属性 只不过 getters是用于vuex的计算属性 |
getters: {
changeAge(state) {
state.name++
return state.name
}
},
<p>{{changeDate1}}</p>
<script>
import { mapGetters } from 'vuex'
export default {
computed: {
...mapGetters([
'changeDate1'
])
},
</script>
modules 的使用方法及场景
- 其他模块相当于一个另一个vuex,可以将庞大的数据,分类封装成单独模块,然后引入到一个模块,提高代码的维护性
- 封装模块的例子
-
const moduleA = {
state: {
data: 'moduleA',
data1: true
},
getters: {
changeDate1() {
return '你是个麻瓜'
}
},
mutations: {},
actions: {}
}
export default moduleA
- 将封装好的模块引入
```javascript
modules: {
moduleA
},
<p>{{changeDate1}}</p>
<p>{{moduleA.data}}</p>
<script>
import { mapState } from 'vuex'
export default {
computed: {
...mapState([
'moduleA'
]),
...mapGetters([
'changeDate1'
])
},
</script>
plugin 的使用方法及场景
- 安装插件前电脑上需要有yarn或者npm或cnpm
- 安装插件
yarn add vuex-persistedstate --save
npm i vuex-persistedstate --save
cnpm i vuex-persistedstate --save
import createPersisted from 'vuex-persistedstate'
plugins: [
createPersisted()
]
注:vuex-persistedstate此插件是vuex的数据持久化,可以设置其存储个别数据,具体使用方法到npm官网查看https://www.npmjs.com/,进去直接搜索vuex-persistedstate查看