【融职培训】Web前端学习 第7章 Vue基础教程11 vuex

一、Vuex概述

二、基于Vuex的计数器

我们不能直接修改state,需要定义mutation来操作state,示例代码如下所示:

 1 //store.js
 2 import Vue from "vue";
 3 import Vuex from "vuex";
 4 Vue.use(Vuex);
 5 
 6 const store = new Vuex.Store({
 7     state:{
 8         count:0
 9     },
10     mutations:{
11         increment(state){
12             state.count++
13         }
14     }
15 })
16 
17 export default store

将store注入到每一个子组件中。

 1 import Vue from 'vue'
 2 import App from './App.vue'
 3 import store from "./store"
 4 
 5 Vue.config.productionTip = false
 6 
 7 new Vue({
 8   store,
 9   render: h => h(App),
10 }).$mount('#app')

组件通过this.$store.commit()方法可以提交mutation,示例代码如下所示:

 1 <!-- count组件用来操作数据 -->
 2 <template>
 3     <div>
 4         <button @click="increment">+</button>
 5     </div>
 6 </template>
 7 
 8 <script>
 9 export default {
10     methods:{
11         increment(){
12             this.$store.commit("increment");
13         }
14     }
15 }
16 </script>

通过this.$store.state可以直接访问state对象,并进一步获取state中的数据

 1 <!-- Number组件用来显示数据 -->
 2 <template>
 3     <h1>{{number}}</h1>
 4 </template>
 5 
 6 <script>
 7 export default {
 8     computed:{
 9         number(){
10             return this.$store.state.count
11         }
12     }
13 }
14 </script>

这样我们就利用Vuex实现了一个简答的计数器功能。

三、简化获取state

 1 import {mapState} from "vuex";
 2 export default {
 3     // computed:{
 4     //     count(){
 5     //         return this.$store.state.count
 6     //     }
 7     // }
 8     // computed:mapState({
 9     //     count:state=>state.count,
10     //     fruitList:state=>state.fruitList
11     // })
12     computed:mapState(["count","fruitList"])
13 }

四、官方文档

【融职教育】在工作中学习,在学习中工作

猜你喜欢

转载自blog.csdn.net/ITXDL123/article/details/106924069