新建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>
Logo

前往低代码交流专区

更多推荐