新建vue项目
main.js
import Vue from 'vue'
import App from './App.vue'
import store from "@/store";
Vue.config.productionTip = false;
new Vue({
render: h => h(App),
store
}).$mount('#app');
app.vue
<template>
<div id="app">
<h1>根组件
- {{ $store.state.title }}
- {{ $store.state.count }}
-- {{ title }}
-- {{ count }}
</h1>
<input type="text">
<son-a></son-a>
<hr>
<son-b></son-b>
</div>
</template>
<script>
import SonA from "@/components/SonA"
import SonB from "@/components/SonB"
import { mapState} from 'vuex'
export default {
name: 'App',
components:{
SonA,
SonB
},
computed:{
...mapState(['count','title'])
},
created() {
//检查vuex是否安装成功
console.log(this.$store);
console.log(this.$store.state.count);
}
}
</script>
<style>
</style>
index.js
//存放是vuex的相关代码
import Vue from 'vue'
import Vuex from 'vuex'
//插件安装
Vue.use(Vuex);
//创建仓库
const store = new Vuex.Store({
//通过state可以提供数据
//严格模式,上线时需要关闭,否则影响性能
strict:true,
state:{
title:'仓库大标题',
count:100
},
//通过mutation,可以提供修改数据的方法
mutations:{
//加法,第一个参数,都是state
addOne(state){
state.count += 1;
},
addFive(state){
state.count += 5;
},
changeTitle(state){
state.title = '小标题';
}
}
});
//导出给main.js使用
export default store;
//获取store
// 1 this.$store
// 2 import 导入 store
//模板中 {{ $store.state.xxx}}
//组件逻辑中 this.$store.state.xxx
//js模板中 store.state.xxx
SonA.vue
<template>
<div class="box">
<h2>SonA子组件</h2>
从Vuex中获取的值: <label for="">{{ $store.state.count }}</label>
<br>
<button @click="addOne">值 + 1</button>
<button @click="addFive">值 + 5</button>
<button @click="changeFn">改标题</button>
</div>
</template>
<script>
export default {
name: "SonA",
methods:{
handleAdd(){
//错误代码,不可以这样使用
//this.$store.state.count++
//应该通过mutation核心概念,进行数据修改
},
addOne() {
//加1
this.$store.commit('addOne');
},
addFive(){
//加5
this.$store.commit('addFive');
},
changeFn(){
//改标题
this.$store.commit('changeTitle');
}
}
}
</script>
<style scoped>
.box{
border: 2px solid #cccccc;
width: 400px;
padding: 10px;
margin: 20px;
}
</style>
SonB.vue
<template>
<div class="box">
<h2>SonB子组件</h2>
从vuex中获取的值:<label for="">{{ count }}</label>
<br>
<button>值 - 1</button>
</div>
</template>
<script>
import { mapState } from 'vuex'
export default {
name: "SonB",
computed:{
...mapState(['count'])
}
}
</script>
<style scoped>
.box{
border: 2px solid #cccccc;
width: 400px;
padding: 10px;
margin: 20px;
}
</style>