Vue教程19:Vue 2.0组件开发模式

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/chencl1986/article/details/85227218

示例代码请访问我的GitHub:
https://github.com/chencl1986/vue-tutorial

该节教程代码可通过npm start运行devServer,在http://localhost:8080/查看效果

Vue 2.0组件开发说明

之前的教程中使用的一直是Vue 1.0的组件写法,接下来的课程都会使用Vue 2.0的语法。
Vue 2.0项目开发都需要通过Webpack进行打包,此时就要通过相关loader进行处理,具体可以查看webpack.config.js中的配置。
所有的组件都是以vue作为后缀。

入口js文件说明

代码示例:/lesson17/src/index.js

index.js主要用来引入住入口组件App.vue,以及路由配置,其余组件都通过App组件引入。

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.js

使用vue-router完成路由配置,并将实例导出,提供给入口index.js中的Vue实例引用,这样在组件中就可以直接使用路由组件和方法。

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.vue

App.vue为项目的入口组件,可以通过它跳转到其他组件,或者通过它引入其他组件。

// 此处书写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>

猜你喜欢

转载自blog.csdn.net/chencl1986/article/details/85227218
今日推荐