vue状态管理与vuex

Laughing
2021-05-09 / 0 评论 / 1,036 阅读 / 搜一下 / 正在检测是否收录...

安装vuex

npm i vuex -s

创建数据仓库

创建store文件夹,并在文件夹下创建index.js文件

import Vue from 'vue'
import Vuex from 'vuex'

Vue.use(Vuex)

export default new Vuex.Store({
    state: {
        count: 0
    },
    mutations: {
        increment: state => state.count++,
        decrement: state => state.count--
    }
})

引入数据仓库

main.js中引入我们定义的数据仓库。

import Vue from 'vue'
import App from './App.vue'
import store from '@/store'

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

使用

<template>
  <div id="app">
    {{ count }}
    <button @click="increment">++</button>
    <button @click="decrement">--</button>
  </div>
</template>

<script>
import popup from "./components/popup.vue";
export default {
  components: { popup },
  name: "app",
  data() {
    return {};
  },
  mounted: function () {},
  computed: {
    count() {
      return this.$store.state.count;
    },
  },
  methods: {
    increment: function () {
      this.$store.commit('increment')
    },
    decrement: function () {
      this.$store.commit('decrement')
    },
  },
};
</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>

每次点++按钮,count自动+1

1

评论 (0)

取消
  1. 头像
    Judy
    Windows 7 · Google Chrome

    WordPress标题自动翻译英文插件LS_baidu_translator_木子网
    http://situspokersport.com

    回复