創建新項目 安裝 vuex 後 替換文件可使用 vuex
create vuex1 // 創建項目
cd vuex1 // 進入項目
npm i // 安裝依賴項
npm i vuex // 安裝 vuex
寫入文件:
src\store\index.js
src\components\HelloWorld.vue
src\store\index.js
import Vue from 'vue';
import Vuex from 'vuex';
Vue.use(Vuex);
const state = { // state數據
week: '週一'
}
const getters = { // 相當於計算屬性
getweek: function (state) {
console.log(state.week);
return state.week.replace('周', '星期')
}
}
const mutations = { //mutations定義同步操作的方法
mutWeek(state, str) {
state.week = '今天是:' + str;
}
}
const actions = { // actions 定義異步操作的方法
actWeek(context, str) {
context.commit('mutWeek', str);
}
}
export default new Vuex.Store({
state,
mutations,
actions,
getters
})
src\components\HelloWorld.vue
<template>
<div class="hello">
<div>home的子組件</div>
<br />
<button @click="btn1">按鈕 mapMutations</button>
<button @click="btn2">按鈕 mapActions</button>
<hr />
<!-- 把store.state的值直接顯示 -->
<div>mapState:{{this.$store.state.week}}</div>
<br />
<!-- 把getters的值直接顯示 -->
<div>mapGetters: {{getweek}}</div>
<hr />
</div>
</template>
<script>
// 把 getters mutations acitons 引入
import { mapGetters, mapMutations, mapActions } from "vuex";
export default {
computed: {
...mapGetters(["getweek"]) // mapGetters是指store裏面的getters 的 getweek 方法
},
props: {
msg: String
},
data() {
return {
falg: true
};
},
methods: {
...mapActions(["actWeek"]), // 這裏mapActions 的 actWeek 是指store裏面的actions裏的actWeek 方法
...mapMutations(["mutWeek"]), // 這裏mapMutations 的 mutWeek 是指store裏面的mutations裏的 mutWeek 方法
btn1() {
// 點擊後 執行mutWeek方法,會把值傳入 store.mutWeek方法 改變 state.week的值
this.mutWeek("週三 Mut"); // 執行 store裏面的 mutWeek 同步方法 傳入值
},
btn2() {
this.actWeek("週五 Act"); // 執行 store裏面的 actWeek 異步方法 傳入值
}
}
};
</script>
<style scoped lang="scss">
.hello {
background-color: rgb(86, 168, 201);
}
button {
margin: 0 10px;
}
</style>
src\main.js
import Vue from 'vue'
import App from './App.vue'
import './registerServiceWorker'
import router from './router'
import store from './store' //引入 創建的store倉庫
Vue.config.productionTip = false
new Vue({
router,
store, //將store掛載到vue
render: h => h(App)
}).$mount('#app')