免責事項:この記事への異議を持っている場合は、記事にコメントを記入してくださいはでコメントしています。あなたはこの記事が面白い発見した場合は、共有し、転送、またはあなたが見ることができ、あなたが認識し、私たちの記事を励ましてください。遠く遠くプログラミングの誰もこの道を、願っています。https://blog.csdn.net/weixin_44369568/article/details/91459231
Vuex
1. vuexは何ですか?
- すべてのVuexアプリケーションの心臓部は、(倉庫)を格納することです。「ストア」基本的に、アプリケーションの状態(状態)のほとんどが含まれていた容器です。
2、vuex初期化
(1)vuexをダウンロード
cnpm i vuex -D
(2)店舗のフォルダ(ストア/ index.js)を構築
// 初始化vuex
import Vue from 'vue';
import Vuex from 'vuex';
// 引入module
import app from './module/app';
Vue.use(Vuex);
// 生成一个vuex实例
export default new Vuex.Store({
modules: {
app
}
})
(3)データを格納するために使用されるフォルダに保存フォルダ内のモジュールファイル(ストア/モジュール/ app.js)を構築
// 存放数据的地方
const state = {
num: 100
}
// 派生数据(很少用)
const getters = {
doubleNum(state){
return state.num*2
}
}
// 同步改变
const mutations = {
changeNum(state, payload){
state.num = payload;
}
}
// 异步改变
const actions = {
<!--changeNumAsync(context, payload){-->
<!--}-->
changeNumAsync({commit}, payload){
commit('changeNum', payload)
}
}
export default {
// 命名空间
namespaced: true, // 配合module使用
state,
actions,
getters,
mutations
}
(4)main.jsで店舗内に導入されています
import Vue from 'vue'
import App from './App.vue'
import store from './store'
new Vue({
el: '#app',
store,
render: h => h(App)
})
(5)ページを使用します
<template>
<div>
<button @click="changeNum('+')">+</button>
<span>{{num}}</span>
<button @click="changeNum('-')">-</button>
</div>
</template>
<script>
export default {
name: 'app',
computed: {
num() {
return this.$store.state.app.num
}
},
methods: {
changeNum(type) {
if (type == '+') {
// this.$store.commit('changeNum', this.num+1)
this.$store.dispatch('changeNumAsync', this.num+1)
} else {
this.$store.commit('changeNum', this.num-1)
}
}
},
mounted(){
console.log(this.$store)
}
}
</script>