前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >关于vueX的应用

关于vueX的应用

作者头像
random_wang
发布2019-09-11 16:26:39
2780
发布2019-09-11 16:26:39
举报
文章被收录于专栏:randomrandom
代码语言:javascript
复制
<!-- 接一篇文章 vue开发看这篇文章就够了 https://segmentfault.com/a/1190000012692321 -->
<!-- 
    vuex 我们把它叫做状态管理 ‘状态’一词来源与react 在react中数据在state中 实际上也就是"数据管理"
    vuex解决了大型项目的组件间的通信问题 实际上也就是数据中介 所有的数据增删改查全部通过vuex来实现 
  -->
  <div id="app">
    <!--页面总调用state中的数据-->
    store 中的数据:{{ $store.state.count }}

    <button @click="fn">修改store中的数据</button>
    <!-- 页面中条用getters中的数据 -->
    <p>getters的使用:{{ $store.getters.doneTodosCount }}</p>
  </div>

    <!--引入包-->
  <script src="./vue.js"></script>
  <script src="./vuex.js"></script>


  <script>
    // 创建store,用来存储项目中使用的数据(理解为数据仓库 仓库中有管理数据的方法)。
    // 也就是说 整个应用中的数据,都应该交给 store 来管理
    // 开发环境下 引入vuex那需要use一下 Vue.use( vuex)
    
    const store = new Vuex.Store({
      // state即状态,也就是组件中的data(数据)
      state: {
        count: 0,

        todos: [
          { id: 1, text: '...完成', done: true },
          { id: 2, text: '...完成', done: true },
          { id: 3, text: '...完成', done: true },
          { id: 4, text: '...完成', done: true },
          { id: 5, text: '...未完成', done: false }
        ]
      },

      // getters 就是 store 的计算属性,用法与计算属性相同!!!
      getters: {
        doneTodosCount(state) {
          return state.todos.filter(todo => todo.done).length
        }
      },

      // 注意:state中的数据只能通过 mutations 来修改!!!
      // 也就是:数据由 store 提供,同样的修改数据方法也是由 store 来提供的,这就是:mutations
      mutations: {
        increment(state) {
          // 参数 state即:上面的state,也就是数据
          state.count++
        },

        // payload 表示提交这个方法的时候,传递的数据,最好是一个对象
        increment2(state, payload) {
          state.count += payload.num
        }
      }
    })

    /* 
    使用 store 中的数据:
    
    修改数据:store.commit('increment')
    读取数据:store.state.count
    */

    var vm = new Vue({
      el: '#app',
      data: {
        
      },

      methods: {
        fn() {
          // this.$store.commit('increment')
          //通过commit触发mutations中的方法  参数一:方法名 参数二:传递数据
          this.$store.commit('increment2', {num: 3})
        }
      },
      // 将 store 与Vue实例关联到一起
      store: store
    })
  </script>
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档