20201019李权
Vuex:
VueX是一个状态管理的插件,可以解决不同组件之间的数据共享和数据持久化的问题,使用VueX来保存需要管理的状态值,值一旦被修改,所有引用该值的地方就会自动跟新。
状态管理模式:
状态管理模式其实就是集中存储管理应用的所有组件的状态
state:管理所有组件共享的数据
代码:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
//state是状态层都是一些大家都使用的数据
state: {
num:100,
},
})
是响应式渲染,让state数据改变的时候,view视图也会随之改变,注意修改state的只能在multation中进行显示修改
mapState:用来结构数据,结构store里面的数据
他是一个方法。
<template>
<div class="home">
<h1>this is home</h1>
<h2>{{this.$store.state.num}}</h2>
<h2>{{num}}</h2>
</div>
</template>
<script>
import {mapState} from 'vuex';
export default {
name: 'Home',
// computed: {
// //computed是一个对象,对象里面接一些方法
// num(){
// return this.$store.state.num
// }
// //使用mapState来解构数据
// },
computed:mapState(['num']),
}
</script>
另外一个方法:
<template>
<div class="home">
<h1>this is home</h1>
<h2>{{this.$store.state.num}}</h2>
<h2>{{num}}</h2>
</div>
</template>
<script>
import {mapState} from 'vuex';
export default {
name: 'Home',
// computed: {
// //computed是一个对象,对象里面接一些方法
// num(){
// return this.$store.state.num
// }
// //使用mapState来解构数据
// },
computed:{
paly(){},
...mapState(['num'])
}
}
mutation的属性:
定义一些操作state的同步方法,是唯一修改state的值的方法
使用mutations的方法需要使用commit来触发
mapmutations是用来结构mutations的方法,它也是一个函数
用法:
<template>
<div class="admin">
<h1>this is Admin</h1>
<h2>{{this.$store.state.num}}</h2>
<h2>{{this.$store.getters.sum}}</h2>
<!-- mutations定义的方法要用commit来触发 -->
<button v-on:click="$store.commit('addNum')">num++</button>
<button @click="addNum">num++</button>
</div>
</template>
<script>
import {mapMutations} from 'vuex';
export default {
name: 'Admin',
data(){
return{
}
},
methods: {
...mapMutations(['addNum'])
},
}
</script>
actions:
主要用来操作一些state的异步方法。
actions: {
addNumAsync(context){
new Promise((res,rej)=>{
setTimeout(()=>{
res()
},1000)
}).then((data)=>{
//异步执行完之后调用context 中的mutations
context.commit('addNum')
}).catch((err)=>{
console.log(err);
})
}
},
近期评论