vuex小记

学了vuex后,发现其对于状态的管理,非常棒,虽然我也用得不熟练O(∩_∩)O,

首先,当然是安装vuex了,

1,npm i vuex --save.

2.在src下创建一个vuex的文件夹,并在文件夹下新建一个store.js的文件,接下来,就是编辑这个文件

   (1)引入vue和vuex

      import Vue from 'vue'

      import Vuex from 'vuex'

      (2)使用vuex

      Vue.use(Vuex)

3.接下来,开始使用了,,,,,,(~ ̄▽ ̄)~

     (1)在store.js文件中新增一个常量对象,

          const state = { count:1 }

          用export default 封装代码,让外部可以引用

         export default new Vuex.Store({

         state

})

    (2)在compoents文件夹下新建一个count.vue的文件,并在模板中引用store.js文件,并在模板中使用{{$store.state.count}}输出count的值

    <template>

       <div>

          <h2>{{$store.state.count}</h2>

</div>  

<script>

    import store from '@/vuex/store'

</script>

</template>

 

(3)在store.js文件中,加入两个改变state的方法

  const mutations = {

    add(state){

      state.count++

},

reduce(state){

  state.count--

}

}

并在export default 中添加mutations

(4)在count.vue中,添加两个按钮,并调用mutations中的方法

<div>

    <button @click="$store.commit('add')">+</button>

 <button @click="$store.commit('reduce')">-</button>

</div>

state的操作就是这样的,推荐观看技术胖的vue视频,简单,好学。附上他的vuex的网址http://jspang.com/post/vuex.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章