zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    卡特兰数
    割点和桥
    子序列(超级水)
    react 进行时
    又开启react之路
    关于特殊字体
    react 组件传值
    git 的安装和项目建立
    ES6 let and const
    js封装的一行半显示省略号(字数自由控制)
  • 原文地址:https://www.cnblogs.com/zhangqing979797/p/10067918.html
Copyright © 2011-2022 走看看