学习项目-前端-第九课:vuex

一、install vuex(vue-cli)-->command

1、vue init webpack vuexdemo

2、cnpm install vuex --save

3、npm run dev

二、interpretation vuex

1、src/store/index.js(priority focus--core)

 1 import Vue from 'vue'
 2 import Vuex from 'vuex'
 3 
 4 Vue.use(Vuex)
 5 
 6 const store = new Vuex.Store({
 7     state: {
 8         count: 0
 9     },
10     mutations: {
11         increment(state,x){
12             state.count += x;
13         }
14     },
15     actions: {
16         increment(context){
17             context.commit('increment',10);
18         }
19     },
20     getters: {
21         remark(state){
22             if(state.count < 50){
23                 return 'Come On!';
24             }else if(state.count < 100){
25                 return 'You Are Great!';
26             }else{
27                 return 'You Are God!';
28             }
29         }
30     }
31 })
32 
33 export default store

2、src/main.js

 1 // The Vue build version to load with the `import` command
 2 // (runtime-only or standalone) has been set in webpack.base.conf with an alias.
 3 import Vue from 'vue'
 4 import App from './App'
 5 import router from './router'
 6 import store from './store'
 7 
 8 Vue.config.productionTip = false
 9 
10 /* eslint-disable no-new */
11 new Vue({
12   el: '#app',
13   router,
14   store,
15   components: { App },
16   template: '<App/>'
17 })

3、src/components/HelloWorld.vue

 1 <template>
 2   <div >
 3     {{$store.state.count}}
 4     <button @click="addCount">test</button>
 5     {{ $store.getters.remark }}
 6   </div>
 7 </template>
 8 
 9 <script>
10 export default {
11   methods: {
12     addCount(){
13       // this.$store.commit('increment',10);
14       this.$store.dispatch('increment');  
15       console.log(this.$store.state.count);
16     }
17   }
18 }
19 </script>

4、src/components/show.vue

 1 <template>
 2     <div>
 3         show : {{ $store.state.count }}
 4     </div>
 5 </template>
 6 
 7 <script>
 8 export default {
 9     methods: {
10 
11     }
12 }
13 </script>

5、src/router/index.js

 1 import Vue from 'vue'
 2 import Router from 'vue-router'
 3 import HelloWorld from '@/components/HelloWorld'
 4 import Show from '@/components/show'
 5 
 6 Vue.use(Router)
 7 
 8 export default new Router({
 9   routes: [
10     {
11       path: '/',
12       name: 'HelloWorld',
13       component: HelloWorld
14     },
15     {
16       path: '/show',
17       name: 'Show',
18       component: Show
19     },
20   ]
21 })

 

posted @ 2020-07-19 08:59  遥~  阅读(154)  评论(0编辑  收藏  举报