如果你之前使用过vue.js,你一定知道在vue中各个组件之间传值的痛苦,在vue中我们可以使用vuex来保存我们需要管理的状态值,值一旦被修改,所有引用该值的地方就会自动更新,那么接下来我们就来学习一下vuex是如何修改状态值的。
1. 搭建Demo
使用vue create 项目名创建一个项目,在src根目录下创建一个components目录并在该目录下面创建2个组件:header.vue,content.vue,在App.vue根组件中进行引入然后展示,删除不必要的组件。
}
display: inline-block;
width: 32px;
height: 32px;
cursor: pointer;
}
.header span:first-child{
background: red;
}
.header span:last-child {
background: blue;
}
header.vue
mounted(){
}
}
height: 600px;
text-align: center;
line-height: 600px;
}
content.vue
import Content from"./components/content";
exportdefault{//注册组件
components: {
Header,
Content
}
};
App.vue
页面效果:
下面需要实现点击红色按钮使得背景变为红色,点击蓝色按钮使得背景变成蓝色,下面使用vuex实现。
2. 设置和获取仓库中的数据
先安装vuex。
yarn add vuex
在src根目录下创建store,然后创建一个index.js文件。
import Vuex from "vuex";
import Vue from"vue";//注册插件
Vue.use(Vuex);//创建仓库实例
const store = newVuex.Store({//仓库的数据
state: {
test_data:"this is some test data",
color:"light-green"},//同步修改state的值
mutations: {//mutations下的方法第一个参数是固定state
//第二个参数是传进来的参数
setColor(state, color) {
state.color=color;
}
}
});
exportdefault store;
stroe/index.js
实现后的代码
methods: {
handleClick(color){//不推荐使用这个方法来修改state的值
//this.$store.state.color = color;
//this.$store.commit调用mutations下面的方法
//第一个参数就是mutations下面的的具体方法
//第二个参数就是传递给方法的参数
this.$store.commit("setColor", color)
}
}
}
display: inline-block;
width: 32px;
height: 32px;
cursor: pointer;
}
.header span:first-child{
background: red;
}
.header span:last-child {
background: blue;
}
header.vue
mounted() {//this.$store当把仓库引入到main.js的时候,组件可以通过this.$stroe获取仓库的数据
console.log(this.$store);
}
};
height: 600px;
text-align: center;
line-height: 600px;
}
content.vue
import Vue from ‘vue‘import App from‘./App.vue‘import store from‘./store‘Vue.config.productionTip= false
newVue({
render: h=>h(App),
store,
}).$mount(‘#app‘)
main.js
原文:https://www.cnblogs.com/replaceroot/p/11171517.html