Vue教程19:Vue 2.0組件開發模式

閱讀更多系列文章請訪問個人GitHub博客,示例代碼請訪問這裏

該節教程代碼可經過npm start運行devServer,在http://localhost:8080/查看效果css

Vue 2.0組件開發說明

以前的教程中使用的一直是Vue 1.0的組件寫法,接下來的課程都會使用Vue 2.0的語法。 Vue 2.0項目開發都須要經過Webpack進行打包,此時就要經過相關loader進行處理,具體能夠查看webpack.config.js中的配置。 全部的組件都是以vue做爲後綴。html

入口js文件說明

代碼示例:/lesson17/src/index.jsvue

index.js主要用來引入住入口組件App.vue,以及路由配置,其他組件都經過App組件引入。webpack

import Vue from 'vue';
// 主入口組件
import App from './App.vue';
// 引入路由配置
import router from './routers';

let vm=new Vue({
  el: '#div1',
  data: {},
  components: {App},
  router, // 將路由表掛載到Vue實例,在組件中能夠直接使用路由組件和功能
  template: `
    <App/>
  `
})
複製代碼

路由配置說明

代碼示例:/lesson17/src/routers/index.jsgit

使用vue-router完成路由配置,並將實例導出,提供給入口index.js中的Vue實例引用,這樣在組件中就能夠直接使用路由組件和方法。github

import Vue from 'vue';
import Router from 'vue-router';

// 引入頁面組件 
import Index from '@/index.vue';
import News from '@/news.vue';

// 全局使用Router
Vue.use(Router);

// 配置路由
export default new Router({
  routes: [
    {
      path: '/',
      name: 'index',
      component: Index
    },
    {
      path: '/news',
      name: 'news',
      component: News
    }
  ]
})
複製代碼

App.vue組件說明

代碼示例:/lesson17/src/App.vueweb

App.vue爲項目的入口組件,能夠經過它跳轉到其餘組件,或者經過它引入其餘組件。vue-router

// 此處書寫template模板,支持html等多種語言,等同於Vue.component中的template屬性
<template lang="html">
  <div>
    <!-- 將組件寫入模板,兩種寫法都兼容 -->
    <CmpTest />
    <cmp-test />
    <!-- 路由跳轉連接,因爲路由已經在入口index.js中掛載,組件中能夠直接使用 -->
    <router-link :to="{ name: 'index', params: {} }">首頁</router-link>
    <router-link :to="{ name: 'news', params: {} }">新聞</router-link>
    <router-view/>
  </div>
</template>

// 此處書寫JavaScript代碼,等同於Vue.component代碼
<script>
// 引入其餘組件
import CmpTest from './components/cmp.vue'

// 默認導出Vue組件
export default {
  name: 'app',  // name屬性爲組件提供了一個ID,調試時的報錯信息將顯示該名稱
  data(){
    return {a: 12}
  },
  components: {
    CmpTest
  }
}
</script>

// 此處書寫樣式,支持css、less等其餘語言
<style lang="css" scoped>
</style>
複製代碼
相關文章
相關標籤/搜索