兄弟组件使用EventBus进行传递参数,子父组件相互传值使用v-bind,v-on传值。
但是如果节点特别的多,而且这些参数要跨多个组件,那这些变量就不太好修改,要一个个节点相互通信达到效果,因此vuex就产生了。
在项目中引入Vuex
1、安装依赖
如果使用了脚手架的话,一般已经搭建好了。
npm install vuex --save
2、创建文件
在src目录下创建一个store文件夹,然后创建一个index.js文件。该文件内容如下:
//引入vue和vuex
import Vue from 'vue';
import Vuex from 'vuex';
//将vuex和vue绑定,让vue可以使用vuex
Vue.use(Vuex);
//将store对象暴露成默认对象
export default new Vue.Store({
//声明全局的数据对象
state:{
属性名:属性默认值
},
//mutations中不能以异步的形式修改state中的值,因为浏览器的dev-tool插件监听不到,所以就需要actions,而actions中不能直接操作state的变量,因此可以在actions中进行异步操作,然后调用mutations中的方法。
actions:{},
//组件引用state中的变量,不能直接修改,可以通过mutations暴露出去的方法修改。
mutations:{}
})
3、配置Vuex,让所有的组件都可以访问到。
在main.js文件中将Vuex配置成全局访问。
在原有内容上再补充一些,内容如下:
//引入刚刚之前在store文件夹下配置的内容
import store from "./store"
new Vue({
sotre
})
例如,我写的一个案例中的配置。
// The Vue build version to load with the `import` command
// (runtime-only or standalone) has been set in webpack.base.conf with an alias.
import Vue from 'vue'
import App from './App'
import router from './router'
//vue集成elements-ui的依赖,设置全局样式
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
Vue.use(ElementUI)
//引入vuex
import store from "./store";
//引入全局的axios请求
import axios from 'axios'
//将axios添加进全局属性中
Vue.prototype.$http = axios
//Vue.prototype.baseURL = process.env.API_ROOT;
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
//导入成所有组件可用
store,
components: { App },
template: '<App/>'
})
4、组件中使用Vuex
在组件中就可以直接使用,不需要再额外引入其他的包了。
例如:
<span>{{$store.state.num}}</span>
或者
<span>{{this.$store.state.num}}</span>
num就是定义在store/index.js文件内state的全局变量。
例如:store/index.js文件的内容
import Vue from 'vue';
import Vuex from 'vuex'
Vue.use(Vuex);
export default new Vuex.Store({
//声明全局变量
state: {
num:10
},
actions: {},
mutations: {}
}
)