首页 > 代码库 > vue + vue-router + vue-resource 基于vue-cli脚手架 --->笔记

vue + vue-router + vue-resource 基于vue-cli脚手架 --->笔记

ps: 基于Vue2.0 npm的vue-cli脚手架

在vue-router中路由路径的简写代码:

点击打开项目 > build > webpack.base.conf.js 找到webpack.base.conf.js文件修改即可
  值得注意的是,修改了alias下的引用路径后,要重启项目(npm run dev),否则将会报错

function resolve (dir) {
  return path.join(__dirname, ‘..‘, dir)
}

module.exports = {
  entry: {
    app: ‘./src/main.js‘
  },
  output: {
    path: config.build.assetsRoot,
    filename: ‘[name].js‘,
    publicPath: process.env.NODE_ENV === ‘production‘
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  resolve: {
    extensions: [‘.js‘, ‘.vue‘, ‘.json‘],
    alias: {
      ‘vue$‘: ‘vue/dist/vue.esm.js‘,
      ‘@‘: resolve(‘src‘),
      ‘components‘: resolve(‘src/components‘),
    }
  },

 

下面代码中即用到简写的路由路径:components

ps: 值得注意的是1.0中路由默认展现第一个组件的go(‘/goods‘)方法,在2.0中不行,可用 导航式编程 router.push(‘/goods‘)
      或者---在路由配置项中进行设置,用 重定向 的方法
      如下 routes 设置项-->  {path: ‘/‘, redirect: goods},即默认进来 ‘/‘ 未加路由地址时,显示 goods 这个组件

导航式编程方法:

import Vue from ‘vue‘;
import VueRouter from ‘vue-router‘;
Vue.use(VueRouter);
import goods from ‘components/goods/goods‘;
import ratings from ‘components/ratings/ratings‘;
import seller from ‘components/seller/seller‘;
const routes = [
  {path: ‘/‘, redirect: goods, name:"商品"},
  {path: ‘/goods‘, component: goods, name: "商品"},
  {path: ‘/ratings‘, component: ratings, name: "评论"},
  {path: ‘/seller‘, component: seller, name: "商家"}
]
export default new VueRouter({
  routes: routes
})

重定向方法:  

import Vue from ‘vue‘;
import router from ‘./router‘;
import App from ‘./App‘;
router.afterEach((to, from, next) => {
  document.title = to.name;
})
router.push(‘/goods‘)
/* eslint-disable no-new */
new Vue({
  el: ‘#app‘,
  router,
  template: ‘<App/>‘,
  components: {App}
});

  

基于vue-router路由切换时,动态显示组件或页面模块的标题方法:

const routes = [
  {path: ‘/‘, redirect: goods, name:"商品"},
  {path: ‘/goods‘, component: goods, name: "商品"},
  {path: ‘/ratings‘, component: ratings, name: "评论"},
  {path: ‘/seller‘, component: seller, name: "商家"}
]
ps: 其中name值,就是上面代码中路由配置的组件的 name
router.afterEach((to, from, next) => {
  document.title = to.name;
})

  

 

 参考地址 https://juejin.im/entry/585377cf8e450a006c53aef1

vue + vue-router + vue-resource 基于vue-cli脚手架 --->笔记