1. 程式人生 > >Vue Vuex state mutations

Vue Vuex state mutations

lang con spa In HR ID all rom script

Vuex
解決不同組件的數據共享,與數據持久化

1.npm install vuex --save
2.新建store.js 並引入vue vuex ,Vue.use(Vuex)
3.state在vuex中用於存儲數據
var state = {
  count:1
}
4.mutations裏放的是方法,主要用於改變state中的數據
var mutations = {
  incCount(){
    ++state.count;
  }
}
5.實例化vuex.Store
  consta store = new Vuex.Store({
    state,
    mutations
  })
6.export default store;
7.組件A中引入store
import store from ‘../store.js‘
8.註冊
mounted(){},
store
9.
通過this.$store.state.count引用屬性
通過this.$store.commit.(‘incCount‘))引用方法

import Vue from vue;
import Vuex from vuex;
Vue.use(Vuex);

var state = {
    count:1
}

const mutations = {
    run(){
        ++state.count;
    }
}

const store = new Vuex.Store({
    state,
    mutations
});




export default store;
<template>
  <div id="app">
    <router-link to="
/home">Home組件</router-link> <router-link to="/news">News組件</router-link> <hr> <router-view></router-view> </div> </template> <script> export default { name: app, data () { return { msg: Welcome to Your Vue.js App } } }
</script> <style lang="scss"> </style>
<template>
    <div id="news">
        News組件
        {{this.$store.state.count}}
    </div>
</template>


<script>
import store from ../utils/store.js
export default {
  data() {
          return{}
  },
  store
};
</script>
<template>
   <div id="home">
        Home組件
        {{this.$store.state.count}}
        <br>
        <button @click="addstate()">添加state</button>
    </div>
</template>

<script>
import store from ../utils/store.js
export default {
  data() {
    return{}
  },
  store,
  methods:{
    addstate(){
      this.$store.commit(run)
    }
  }
};
</script>

Vue Vuex state mutations