vue 项目中 全局使用 mixins
新建mixins文件// src/mixins/index.jslet mixin={data(){return{};},methods:{loadPage(routerName,param){if(param){this.$router.push({name:routerName,query:param});...
·
新建mixins文件
在src
目录下新建mixins
目录。mixins
目录里新建index.js
文件。在这里写一个loadPage
路由跳转方法供全局使用
// src/mixins/index.js
let mixin={
data(){
return{};
},
methods:{
loadPage(routerName,param){
if(param){
this.$router.push({name:routerName,query:param});
}else{
this.$router.push({name:routerName});
}
}
}
};
export default mixin;
把mixins注册全局
在src/main.js
文件加入以下两行
import Mixin from './mixins';
Vue.mixin(Mixin);
加入后,main.js
文件如下
// src/main.js
import Vue from 'vue'
import App from './App'
import router from './router'
import Mixin from './mixins';
Vue.mixin(Mixin);
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
components: { App },
template: '<App/>'
})
使用mixins里的方法
设置路由
// src/router/index.js
import Vue from 'vue'
import Router from 'vue-router'
Vue.use(Router)
export default new Router({
mode:'history',
routes: [
{
path:'/',
redirect:'/index'
},
{
path: '/about',
name: 'About',
component:resolve => require(['@/pages/About'],resolve)
},
{
path: '/index',
name: 'Index',
component:resolve => require(['@/pages/Index'],resolve)
},
{
path: '/product',
name: 'Product',
component:resolve => require(['@/pages/Product'],resolve)
}
]
})
页面调用mixins
里的loadPage
方法
<p @click="loadPage('Index')">Index</p>
Index
页面如下
// src/pages/Index
<template>
<div>
<p>这是index页面</p>
<p @click="loadPage('Index')">Index</p>
<p @click="loadPage('About')">About</p>
<p @click="loadPage('Product')">Product</p>
</div>
</template>
<script>
export default{
}
</script>
<style>
</style>
更多推荐
已为社区贡献8条内容
所有评论(0)