Vuex是什么?

Vuex 是一个专为 Vue.js 应用程序开发的状态管理模式。它采用集中式存储管理应用的所有组件的状态,并以相应的规则保证状态以一种可预测的方式发生变化。



如图所示:

Vue Components可通过State来获取公共数据

如果需要修改数据的话,需要经过:  Actions以及Mutations来进行修改

下面我们使用实例测试一下:

首先我们安装Vuex
npm install vuex --save
然后在src目录下创建store目录,建立一个index.js文件,导入Vuex以及Vue
import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export default new
Vuex.Store({ state: { city: '湖南' }, actions: { changeCity (ctx,city) {
ctx.commit('changeCity',city) } }, mutations: { changeCity (state,city) {
state.city = city } } })
然后在main.js中引入store
import Vue from 'vue' import App from './App' import router from './router'
import 'styles/reset.css' import 'styles/border.css' import
'styles/iconfont.css' import fastclick from 'fastclick' import VueAwesomeSwiper
from 'vue-awesome-swiper' import 'swiper/dist/css/swiper.css' //导入store import
store from './store' Vue.config.productionTip = false
fastclick.attach(document.body) Vue.use(VueAwesomeSwiper) /* eslint-disable
no-new */ new Vue({ el: '#app', router, //引入store(Vuex框架进行传值) store,
components: { App }, template: '<App/>' })
当我们需要获取数据时,可以直接通过
{{this.$store.state.city}}
直接获取

当我们需要改变该数据时:

可以给其绑定一个事件,并传入新的值:



点击事件触发后直接通过dispatch触发index.js中actions中的changCity方法并将新值传递过去:
methods:{ handleCityClick (city) { this.$store.dispatch('changeCity',city)
this.$router.push('/') } }
这样就能让两个页面之间进行数据传递了



数据传递完成了,接下来我们讲解一下以上应用到的页面跳转

这里我们使用了路由的编程式跳转

路由router已经在webpack创建项目时已经导入,这里就不需要导入,直接使用

this.$router.push("/")就可以跳转到相应的页面。

 

 

 

 

 

友情链接
KaDraw流程图
API参考文档
OK工具箱
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:[email protected]
QQ群:637538335
关注微信