data 获取vuex_vuex之仓库数据的设置与获取

本文介绍了如何在Vue.js项目中使用Vuex管理状态,通过创建一个简单的Demo,展示了如何设置和获取Vuex仓库中的数据,包括安装Vuex、定义state和mutations,以及在组件中使用this.$store进行数据交互。
摘要由CSDN通过智能技术生成

如果你之前使用过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

Content

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

Content

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值