最近閑著沒事在網上看了一個實戰項目,自己也對應著新版本的2.X版本的Vue.js的官方API仔細研究過,但是還是發現有一些API中沒有提到的坑~。
關于vue-router的使用方法請查看官方文檔。
首先我們肯定會看文檔,router到底怎么用,我們就看下官方的例子
HTML
<div id="app">
<h1>Hello App!</h1>
<p>
<!-- 使用 router-link 組件來導航. -->
<!-- 通過傳入 `to` 屬性指定鏈接. -->
<!-- <router-link> 默認會被渲染成一個 `<a>` 標簽 -->
<router-link to="/foo">Go to Foo</router-link>
<router-link to="/bar">Go to Bar</router-link>
</p>
<!-- 路由出口 -->
<!-- 路由匹配到的組件將渲染在這里 -->
<router-view></router-view>
</div>
JavaScript
// 0. 如果使用模塊化機制編程,導入Vue和VueRouter,要調用 Vue.use(VueRouter)
// 1. 定義(路由)組件。
// 可以從其他文件 import 進來
const Foo = { template: '<div>foo</div>' }
const Bar = { template: '<div>bar</div>' }
// 2. 定義路由
// 每個路由應該映射一個組件。 其中"component" 可以是
// 通過 Vue.extend() 創建的組件構造器,
// 或者,只是一個組件配置對象。
// 我們晚點再討論嵌套路由。
const routes = [
{ path: '/foo', component: Foo },
{ path: '/bar', component: Bar }
]
// 3. 創建 router 實例,然后傳 `routes` 配置
// 你還可以傳別的配置參數, 不過先這么簡單著吧。
const router = new VueRouter({
routes // (縮寫)相當于 routes: routes
})
// 4. 創建和掛載根實例。
// 記得要通過 router 配置參數注入路由,
// 從而讓整個應用都有路由功能
const app = new Vue({
router
}).$mount('#app')
然后我們在實際項目中這么寫時,可能會報錯,我們來看代碼:
下面的代碼是通過vue-cli腳手架自動生成的
// 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 VueRouter from 'vue-router'
import VueResource from 'vue-resource'
import Goods from 'components/goods/goods'
import Ratings from 'components/ratings/ratings'
import Seller from 'components/seller/seller'
import 'common/stylus/index.styl'
Vue.config.productionTip = false
Vue.use(VueRouter)
Vue.use(VueResource)
const routes = [
{
path: '/goods',
component: Goods
}, {
path: '/ratings',
component: Ratings
}, {
path: '/seller',
component: Seller
}
]
const router = new VueRouter({
linkActiveClass: 'active', routes // (縮寫)相當于 routes: routes
})
router.push('/goods')
const app = new Vue({
router
}).$mount('#app')
我定義了一個路由routes,并且根據官網的例子使用,但是實際結果必然是報錯
1、首先是eslint報錯:http://eslint.org/docs/rules/no-unused-vars 'App' is defined but never used,意思就是說app被定義了但是沒有使用,我們按照官網的例子暫時用不到App組件所以我們暫時將App注釋掉。
2、其次,http://eslint.org/docs/rules/no-unused-vars 'app' is defined but never used,解決這個問題其實很簡單只要我們使用注釋“/ eslint-disable no-unused-vars /”禁用掉它這條規則就可以
/* eslint-disable no-unused-vars */
const app = new Vue({
router
}).$mount('#app')
這樣處理之后,你會發現項目啟動沒有報錯了,但是界面確實一片空白,這是因為實際上我們的路由并沒有掛載到我們的組件上導致的。你需要做的就是如下改動:
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
render: h => h(App)
})
之后項目就會正常運行了,其實這種寫法和下面的結果一樣
/* eslint-disable no-unused-vars */
const app = new Vue({
router,
template: '<App/>',
components: {
App
}}).$mount('#app')
寫法一是傳入了render函數,并將組件App傳入,并以此渲染組件
寫法二是普通的傳入template,和components以此來渲染
官方推薦使用render函數。