vuex初識

main.jsvue

import Vue from 'vue'
import App from './App.vue'
import Vuex from 'vuex'

Vue.config.productionTip = false

Vue.use(Vuex)
const store = new Vuex.Store({
  state: {
    count: 0
  },
  mutations: {
    countIncrease1(state) {
      state.count++
    },
    countIncrease2(state, v) {
      state.count = v;
    }
  }
})

new Vue({
  store,
  render: h => h(App),
}).$mount('#app')

 

App.vueweb

<template>
  <div id="app">
    <!-- <img alt="Vue logo" src="./assets/logo.png">
    <HelloWorld msg="Welcome to Your Vue.js App"/>-->
    <h1>count:{{this.$store.state.count}}</h1>
    <h2>count:{{count}}</h2>
    <button @click="countIncrease1">點我自增</button>
    <button @click="countIncrease2">點我改變</button>
  </div>
</template>

<script>
// import HelloWorld from "./components/HelloWorld.vue";

export default {
  name: "app",
  components: {
    // HelloWorld
  },
  computed: {
    count() {
      return this.$store.state.count;
    }
  },
  methods: {
    countIncrease1() {
      this.$store.commit("countIncrease1");
    },
    countIncrease2() {
      const v = 100;
      this.$store.commit("countIncrease2", v);
    }
  }
};
</script>

<style>
#app {
  font-family: "Avenir", Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>
相關文章
相關標籤/搜索