在使用vue制作单页面应用时,我们有时会将某一个功能单独写在视图外部。
比如信息提示框就是这样的存在,就像App.vue中的这样
<template>
<div id="app1">
<div class="nav-bottom" v-show="$route.meta.navShow">
<!-- 引入公用的头部 header组件 -->
<v-header></v-header>
</div>
<div class="contianer">
<!-- 路由中的几个组件在这里被渲染,默认被渲染的为第一个组件,也就是home组件 -->
<!--动画容器-->
<transition name="fade">
<router-view></router-view>
</transition>
</div>
<!--提示框-->
<div id="tishi" v-bind:style="{opacity:$store.state.tishi_opa3,display:$store.state.tishi_show3}"><span>{{$store.state.tishi_txt}}</span></div>
</div>
</template>
以上可以看到,在contianer视图外面有一个header公用头部和公用提示组件。
现在我们想让提示组件在任何一个vue视图中都可以使用,这时我想到了可否在其他页面里inport App.vue,然后使用App.vue里的方法。
import app_vue from '../App'//利用相对路径引入app.vue模块,即可使用该模块中的模板,变量,方法
可后来我发现虽然我能获取App.vue中的值,但是却无法传递至视图中去。
然后我又想将提示组件里面所有变量全部在main.js中写成全局变量,这样总可以吧。
Vue.prototype.tishi=0;
事实证明我还是想多了,和直接引入App.vue没什么区别。
最后我把目光转向了vuex,终于成功了,不得不说,在全局变量和方法的使用上vuex比vue自己定义的全局好用多了。
下面就介绍如何使用vuex:
首先,当然是安装了,可以用标签,也可以用npm,我用的是后者,文件不大,几秒钟就装好了。
npm install vuex --save
然后在main.js中引入
import Vuex from 'vuex';//引入vuex
引入后还要申明使用:
Vue.use(Vuex);
接着就可以定义了:
//定义vuex
const vuex_store = new Vuex.Store({
state:{
tishi_opa3:0,//提示信息状态
tishi_show3:'none',//提示信息状态
tishi_txt:'提示信息',//提示信息内容
},
mutations:{
show_tishi(state){//提示信息动画
state.tishi_opa3=1;
state.tishi_show3='block';
setTimeout(function(){
state.tishi_opa3=0;
setTimeout(function(){
state.tishi_show3='none';
},1000);
},1000)
},
change_tishi_txt(state,txt){//修改提示文字
state.tishi_txt=txt;
}
}
})
接着注入到模板:
// 创建和挂载根实例
new Vue({
el: '#app',//vue项目在哪个元素下
store:vuex_store, //注入到vue
router: vueRouter,//使用路由
template: '<App></App>',
components: { App }
})
这样,我们就可以在这个vue实例下的所有.vue中使用这个vuex_store了。
如果我们想在.vue中获取变量,则使用
this.$store.state.你定义的变量
调用方法则不一样,这里是提交的方式:
this.$store.commit('change_tishi_txt','首页提示信息');
this.$store.commit('show_tishi');
以上就是本文的全部内容了,仅代表作者个人观点,作为交流学习之用。