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

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