凌的博客

您现在的位置是: 首页 > 前端学习 > Vue > 

Vue

Vue 3.0 第四章 vuex

2022-06-17 Vue 544

安装:

yarn add vuex


//main.js
import {createApp} from 'vue'
import App from './App.vue'
import {createStore} from "vuex"

const store = createStore({
    state() {
        return {
            count: 0
        }
    },
    mutations: {
        increment(state) {
            state.count++
        }
    }
})

const app = createApp(App)
app.use(store)
app.mount('#app')

Home.vue

<template>
  <button @click="increment"> 增加</button>
  <counter></counter>
</template>
<script>
import counter from "../components/Counter.vue"
export default {
  components:{
    counter
  },
  methods: {
    increment() {
      this.$store.commit('increment')
      console.log(this.$store.state.count)
    }
  }
}
</script>


Counter.vue

<template>
  <div>{{ count }}</div>
</template>
<script>
export default {
  computed: {
    count() {
      return this.$store.state.count
    }
  }
}
</script>


文章评论

0条评论