Vuex的第一课
每一個 Vuex 應用的核心就是 store(倉庫)。“store”基本上就是一個容器,它包含著你的應用中大部分的狀態 (state)。Vuex 和單純的全局對象有以下兩點不同:
Vuex 的狀態存儲是響應式的。當 Vue 組件從 store 中讀取狀態的時候,若 store 中的狀態發生變化,那么相應的組件也會相應地得到高效更新。
你不能直接改變 store 中的狀態。改變 store 中的狀態的唯一途徑就是顯式地提交 (commit) mutation。這樣使得我們可以方便地跟蹤每一個狀態的變化,從而讓我們能夠實現一些工具幫助我們更好地了解我們的應用。
#最簡單的 Store
1) Vuex 在組件中的應用
?
<template>
<div class="home">
<p>{{ this.$store.state.count }}</p>
?
<button @click="addFun">開心學習</button>
?
<HelloWorld msg="Welcome to Your Vue.js App" />
</div>
</template>
?
<script>
// @ is an alias to /src
import HelloWorld from "@/components/HelloWorld.vue";
?
export default {
name: "Home",
components: {
HelloWorld
},
methods: {
addFun() {
this.$store.commit("increment");
}
}
};
</script>
2) /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 ++
}
},
actions: {
?
},
modules: {
}
})
?
總結
- 上一篇: 零基础,最完整的WordPress建站教
- 下一篇: 数据就是土地