vuex
vuex官方檔案
// 入口檔案
import Vue from 'vue'
// 配置vuex的步驟
// 1. 運行 cnpm i vuex -S
// 2. 匯入包
import Vuex from 'vuex'
// 3. 注冊vuex到vue中
Vue.use(Vuex)
// 4. new Vuex.Store() 實體,得到一個 資料倉儲物件
var store = new Vuex.Store({
state: {
// 大家可以把 state 想象成 組件中的 data ,專門用來存盤資料的
// 如果在 組件中,想要訪問,store 中的資料,只能通過 this.$store.state.*** 來訪問
count: 0
},
mutations: {
// 注意: 如果要操作 store 中的 state 值,只能通過 呼叫 mutations 提供的方法,才能操作對應的資料,不推薦直接操作 state 中的資料,因為 萬一導致了資料的紊亂,不能快速定位到錯誤的原因,因為,每個組件都可能有操作資料的方法;
increment(state) {
state.count++
},
// 注意: 如果組件想要呼叫 mutations 中的方法,只能使用 this.$store.commit('方法名')
// 這種 呼叫 mutations 方法的格式,和 this.$emit('父組件中方法名')
subtract(state, obj) {
// 注意: mutations 的 函式引數串列中,最多支持兩個引數,其中,引數1: 是 state 狀態; 引數2: 通過 commit 提交過來的引數;
console.log(obj)
state.count -= (obj.c + obj.d)
}
},
getters: {
// 注意:這里的 getters, 只負責 對外提供資料,不負責 修改資料,如果想要修改 state 中的資料,請 去找 mutations
optCount: function (state) {
return '當前最新的count值是:' + state.count
}
// 經過咱們回顧對比,發現 getters 中的方法, 和組件中的過濾器比較類似,因為 過濾器和 getters 都沒有修改原資料, 都是把原資料做了一層包裝,提供給了 呼叫者;
// 其次, getters 也和 computed 比較像, 只要 state 中的資料發生變化了,那么,如果 getters 正好也參考了這個資料,那么 就會立即觸發 getters 的重新求值;
}
})
// 總結:
// 1. state中的資料,不能直接修改,如果想要修改,必須通過 mutations
// 2. 如果組件想要直接 從 state 上獲取資料: 需要 this.$store.state.***
// 3. 如果 組件,想要修改資料,必須使用 mutations 提供的方法,需要通過 this.$store.commit('方法的名稱', 唯一的一個引數)
// 4. 如果 store 中 state 上的資料, 在對外提供的時候,需要做一層包裝,那么 ,推薦使用 getters, 如果需要使用 getters ,則用 this.$store.getters.***
import App from './App.vue'
const vm = new Vue({
el: '#app',
render: c => c(App),
store // 5. 將 vuex 創建的 store 掛載到 VM 實體上, 只要掛載到了 vm 上,任何組件都能使用 store 來存取資料
})
app.vue
<template>
<div>
<h1>è????ˉ App ??????</h1>
<hr>
<counter></counter>
<hr>
<amount></amount>
</div>
</template>
<script>
import counter from "./components/counter.vue";
import amount from "./components/amount.vue";
export default {
data() {
return {};
},
components: {
counter,
amount
}
};
</script>
<style lang="scss" scoped>
</style>
amount.vue
<template>
<div>
<!-- <h3>{{ $store.state.count }}</h3> -->
<h3>{{ $store.getters.optCount }}</h3>
</div>
</template>
<script>
</script>
<style lang="scss" scoped>
</style>
counter.vue
<template>
<div>
<input type="button" value="https://www.cnblogs.com/ygjzs/p/減少" @click="remove">
<input type="button" value="https://www.cnblogs.com/ygjzs/p/增加" @click="add">
<br>
<input type="text" v-model="$store.state.count">
</div>
</template>
<script>
export default {
data() {
return {
// count: 0
};
},
methods: {
add() {
// 千萬不要這么用,不符合 vuex 的設計理念
// this.$store.state.count++;
this.$store.commit("increment");
},
remove() {
this.$store.commit("subtract", { c: 3, d: 1 });
}
},
computed:{
fullname: {
get(){},
set(){}
}
}
};
</script>
<style lang="scss" scoped>
</style>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/162729.html
標籤:JavaScript
下一篇:vue-其他
