局部参数

我们在说局部参数之前,需要知道,new Vuex({}),vuex的参数对象,除了可以罗列modules之外,还可以设置state,mutations,actions,getters,和我们之前设置单一的对象相同

 1 import Vuex from 'vuex'
 2 // 引入vue
 3 import Vue from 'vue'
 4 // 使用vuex
 5 Vue.use(Vuex)
 6 //引入相关的store模块
 7 import news from "./news.js"
 8 import user from "./user.js" 
 9 import sport from "./sport.js" 
10 
11 
12 export default new Vuex.Store({
13     modules: {
14       sport,
15       news,
16       user,
17 
18     },
19     state:{
20         name:'小明'
21     },
22     mutations: {
23         add() {
24             console.log("触发add")
25         }
26     },
27     actions:{},
28     getters:{}
29 
30 })

 

App.vue文件

 1 <template>
 2 <div>
 3     <p>{{$store.state.name}}</p>
 4     <button @click="add">按我</button>
 5 </div>
 6 </template>
 7 <script>
 8   export default {
 9     methods:{
10       add(){
11         this.$store.commit("add")
12       }
13     }
14   }
15 </script>
16 
17 <style lang="scss" scoped>
18 
19 </style>

 

 

我们可以在vue文件中进行引入设置局部参数
比如我们在App.vue中引入vuex,罗列对应的map函数

 1 <template>
 2 <div>
 3  
 4 </div>
 5 </template>
 6 
 7 <script>
 8 
 9 import Vuex from "vuex"
10   export default {
11 
12   mounted(){
13     console.log(Vuex)
14   },
15   }
16 </script>
17 
18 <style lang="scss" scoped>
19 
20 </style>

 

 

 

 

store.js文件

 1 import Vuex from 'vuex'
 2 // 引入vue
 3 import Vue from 'vue'
 4 // 使用vuex
 5 Vue.use(Vuex)
 6 //引入相关的store模块
 7 import news from "./news.js"
 8 import user from "./user.js" 
 9 import sport from "./sport.js" 
10 
11 
12 export default new Vuex.Store({
13     modules: {
14       sport,
15       news,
16       user,
17 
18     },
19     state:{
20         name:'小明',
21         sex:'男'
22     },
23     mutations: {
24         addNum() {
25             console.log("触发了mapMutations")
26         }
27     },
28 
29     actions: {
30         add() {
31             console.log("局部actions")
32         }
33     },
34     getters:{
35         userSex(state){
36             if(state.name=="小明"){
37                 return '男'
38             }
39         }
40     }
41 
42 })

 

App.vue文件

 1 <template>
 2 <div>
 3    <p> {{name}}</p>
 4     <p>{{userSex}}</p>
 5     <p><button @click="add">按我触发mapActions</button></p>
 6     <p><button @click="addNum">按我触发mapMutations</button></p>
 7 
 8 </div>
 9 </template>
10 <script>
11 import { 
12     mapState,
13     mapGetters,
14      mapActions,
15    mapMutations
16 } from "vuex"
17   export default {
18     methods:{
19    ... mapActions([
20      'add'
21    ]),
22      ...mapMutations([
23             'addNum'
24         ])
25 
26     },
27   
28     computed:{
29       ...mapState({
30         name:state=>state.name
31       }),
32       ...mapGetters(['userSex']),
33      
34     }
35   }
36 </script>
37 
38 <style lang="scss" scoped>
39 
40 </style>

 

 

posted @ 2021-09-20 17:10  keyeking  阅读(52)  评论(0编辑  收藏  举报