VUE-X 的传值使用

1.导入vuex   vuex是基于vue 的

1 import Vuex from 'vuex'
2 Vue.use(Vuex);
导入

2.创建store 实例

 1 let store = new Vuex.Store({
 2   state:{
 3     count:1
 4   },
 5   mutations:{
 6     get_count(state){
 7       state.count++;
 8     }
 9   },
10   actions:{
11     //Actions函数接收一个与store实例具有相同方法和属性的context对象
12     //处理异步操作
13     get_count(context){
14       setTimeout(()=>{
15         context.commit('get_count')
16       },500)
17     }
18   }
19 });
store 实例

3.父组件

 1 <template>
 2   <div>
 3     我是首页
 4     <Son></Son>
 5     <button @click="clickHandler">vuex</button>
 6   </div>
 7 </template>
 8 
 9 <script>
10   import Son from "./Son"
11   export default {
12     name:"Home",
13     data(){
14       return {}
15     },
16     components:{
17       Son
18     },
19     methods:{
20       clickHandler(){
21         this.$store.dispatch('get_count')
22       }
23     }
24 
25   }
26 </script>
27 
28 <style>
29 
30 </style>
父组件

4.子组件

 1 <template>
 2   <div>
 3     <h2>我是子组件{{ getCount }}</h2>
 4   </div>
 5 </template>
 6 
 7 <script>
 8   export default {
 9     name:"Son",
10     data(){
11       return{}
12     },
13     computed:{
14       getCount(){
15         return this.$store.state.count
16       }
17     }
18   }
19 </script>
20 
21 <style>
22 
23 </style>
子组件

实际上,vuex传递的首先要经过dispatch 传值 到actions 中 经过actions 的context .commit () 再次传达到mutations中 ,在state 来动态传值    return this.$store.state.count

posted @ 2018-12-04 22:44  逆欢  阅读(144)  评论(0编辑  收藏  举报