vuex 是数据框架(一个插件)(单项数据的改变流程,组件改数据必须先调Action用dispatch方法)
大型项目vue只能承担视图层的主要内容
大量数据传递的时候,往往需要一个数据框架辅助
例子:多个组件之间的传值很困难的时候,如果我们能吧公用的数据放在一个公共的空间
存储,然后某一个组件改变了数据,其他组件能够感知
1.因为vuex做的文件还是比较复杂的,所以我们先创建一个单独的文件夹
/src/store/index.js
import Vue from ‘vue‘ import Vuex from ‘vuex‘ Vue.use(Vuex) export default new Vuex.store({})
2.然后在main.js中引入,便可在所有组件中使用
import store from ‘‘./store" new Vue({ store, //传进根实例 })
3.组件中使用
{{this.$store.state.city}}
4.组件中改变数据
首先组件中调用VUEX中的Actions 用 dispatch方法
然后actions调用Mutations用commit方法
this.$store.dispatch(‘changeCity‘, city) //city为数据 ,派发一个名字叫changCity这样一个Action
//Action需要写在 Store中 export defalut new Store({ state: {} action: { chageCity (ctx, city) {} ctx.commit(‘chageCity‘, city) //ctx为执行上下文 } mutations: { changeCity(‘state‘,‘city‘) { state.city = city } } })
当数据比较简答的时候 可以直接调用mutations
this.$store.commit(‘changeCity‘, city)
1.a标签
<router-link to="/"> </router-link>
2.js window.location.href
this.$router.push(‘/‘)
原文:https://www.cnblogs.com/-constructor/p/12312171.html