58.Vuex使用1 引入

Count.vue

<template>
  <div class="count">
    <h2>当前求和为:{{sum}}</h2>
    <!-- v-model.number收到的数值转换为number -->
    <select v-model.number="n">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
    </select>
    <button @click="increment">+</button>
    <button @click="decrement">-</button>
    <button @click="incrementOdd">当前求求和为奇数再加</button>
    <button @click="incrementWait">等一等再加</button>
  </div>
</template>

<script>
export default {
  name: "TheCount",
  data() {
    return {
      n: 1, // 用户选择的数字
      sum: 0, // 当前的和
    };
  },
  methods: {
    increment() {
      this.sum += this.n;
    },
    decrement() {
      this.sum -= this.n;
    },
    incrementOdd() {
      if(this.sum%2==1){
        this.sum += this.n;
      }
    },
    incrementWait() {
      setTimeout(()=>{
        this.sum += this.n;
      },2000)
    },
  },
};
</script>

<style>
.count {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: space-around;
  width: 300px;
  height: 400px;
}
button,
select,
h2 {
  width: 300px;
  height: 30px;
}
</style>

store/index.js

// 该文件用于创建Vuex中最为核心的store

// 引入Vue
import Vue from 'vue';
// 引入Vuex
import Vuex from 'vuex'; // npm i vuex@3引入vuex3
// 应用Vuex插件
Vue.use(Vuex);

// 准备actions——用于响应组件中的动作
const actions = {};
// 准备mutations——用于操作数据
const mutations = {};
// 准备state——用于存储数据
const state = {};
// 创建store并暴露
export default new Vuex.Store({
    actions,
    mutations,
    state
});

App.vue

<template>
  <div id="app" class="align">
    <count />
  </div>
</template>

<script>
import Count from "./components/Count.vue";
export default {
  name: "App",
  components: { Count },
};
</script>

<style scoped>
</style>

main.js

import Vue from 'vue';
import App from './App.vue' // 引用App
import store from './store/index'; // 引入store
new Vue({
  // 创建vm并使用stroe
  render: h => h(App),
  store,
}).$mount('#app');

你可能感兴趣的:(VUE,vue.js,javascript,前端)