Vuex的第一课
每一個(gè) Vuex 應(yīng)用的核心就是 store(倉(cāng)庫(kù))。“store”基本上就是一個(gè)容器,它包含著你的應(yīng)用中大部分的狀態(tài) (state)。Vuex 和單純的全局對(duì)象有以下兩點(diǎn)不同:
Vuex 的狀態(tài)存儲(chǔ)是響應(yīng)式的。當(dāng) Vue 組件從 store 中讀取狀態(tài)的時(shí)候,若 store 中的狀態(tài)發(fā)生變化,那么相應(yīng)的組件也會(huì)相應(yīng)地得到高效更新。
你不能直接改變 store 中的狀態(tài)。改變 store 中的狀態(tài)的唯一途徑就是顯式地提交 (commit) mutation。這樣使得我們可以方便地跟蹤每一個(gè)狀態(tài)的變化,從而讓我們能夠?qū)崿F(xiàn)一些工具幫助我們更好地了解我們的應(yīng)用。
#最簡(jiǎn)單的 Store
1) Vuex 在組件中的應(yīng)用
?
<template>
<div class="home">
<p>{{ this.$store.state.count }}</p>
?
<button @click="addFun">開心學(xué)習(xí)</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: {
}
})
?
總結(jié)
- 上一篇: 零基础,最完整的WordPress建站教
- 下一篇: 数据就是土地