vuex中state的用法

1.在main.js中引入vuex,
import Vuex from 'vuex'  
Vue.use(Vuex)
new Vue({
  el: '#app',
  router,
  store,(.....別忘記還有它......)
  components: { App },
  template: '<App/>'
})
2.在新建store文件夾,而後在文件夾下新建文件store.js文件
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
  state:{
    count:0,
    title:'佩奇'
  },
})
3.在要用到的組件頁面
<template>
    <div class="box">
     <div class="add" @click="changeCount" >+</div>
      <div style="color:blue">總價爲:{{Allprice}}</div>
      <p>名字:{{title}}</p>
      <p>數量:{{count}}</p>
      <p>單價:{{Oneprice}}</p>
     </div>
 </template>

<script>
 data () {
    return {
      countIndex:'',
      Oneprice:100,
      Acount:0,
  },
computed:{
//獲取咱們要用的值
     count(){
      this.countIndex=this.$store.state.count
      return this.countIndex
    },
    title(){
      return this.$store.state.title
    },
    Allprice(){
      let price=this.countIndex*this.Oneprice
      return price
    },
},
methods:{
    changeCount(){
      this.Acount++;
      this.$store.commit('changeCount',this.Acount)//第一參數爲函數名
      // 第二參數爲改變的值
    }, 
}
</scropt>
4.在store.js頁面中經過mutations去改變值
 mutations:{//要動態的改變本來的值
    changeCount:function (state,count) {//組件的那個改變值得函數名
      state.count=count//從新賦值
      console.log(state.count)
    }
  },
  
  state就是Vuex中的公共的狀態, 我是將state看做是全部組件的data, 用於保存全部組件的公共數據.複製代碼
相關文章
相關標籤/搜索