Vue(十七)模塊化開發
阿新 • • 發佈:2018-01-23
pat center clas 發生 ont mar tex () 原型 模塊化開發
使用vue-cli創建項目
1. vue-router模塊化
引入vue-router
cnpm install vue-router -S
1.1 編輯main.js
import Vue from ‘vue‘ import App from ‘./App.vue‘ import vueRouter from ‘vue-router‘ import routerConfig from ‘./router.config.js‘ //使用vue-router Vue.use(vueRouter); const router = new vueRouter(routerConfig) new Vue({ el: ‘#app‘, render: h => h(App), router })
1.2 編輯App.vue
<template> <div id="app"> <h3>{{msg}}</h3> <div> <router-link to="/home">主頁</router-link> <router-link to="/news">新聞</router-link> </div> <div> <keep-alive> <router-view></router-view> </keep-alive> </div> </div> </template> <script> export default { name: ‘app‘, data () { return { msg: ‘Welcome to Your Vue.js App‘ } }, mounted () { console.log(this.$route) }, watch:{ $route:function(newView,oldView){ console.log(‘路由發生變化,跳轉到‘ + newView.path + ‘,舊的路由地址‘ + oldView.path) } } } </script> <style> #app { font-family: ‘Avenir‘, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } h1, h2 { font-weight: normal; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } </style>
新建文件夾components,創建文件Home.vue,News.vue
1.3 編輯router.config.js
import Home from ‘./components/Home.vue‘ import News from ‘./components/News.vue‘ export default { routes:[ { path:‘/home‘, component:Home }, { path:‘/news‘, component:News } ] }
頁面展示
2. axios模塊化 cnpm install axios -S 使用axios的兩種方式: 方式1:在每個組件中引入axios
<template> <div id="app"> <h3>{{msg}}</h3> <div> <router-link to="/home">主頁</router-link> <router-link to="/news">新聞</router-link> </div> <div> <keep-alive> <router-view></router-view> </keep-alive> </div> <hr> <button @click="send">發送ajax請求</button> </div> </template> <script> import axios from ‘axios‘ export default { name: ‘app‘, data () { return { msg: ‘Welcome to Your Vue.js App‘ } }, mounted () { console.log(this.$route) }, watch:{ $route:function(newView,oldView){ console.log(‘路由發生變化,跳轉到‘ + newView.path + ‘,舊的路由地址‘ + oldView.path) } }, methods: { send(){ axios.get(‘https://api.github.com/users/Somnusy‘) .then(response=>{ console.log(response.data); }).catch(error=>{ console.log(error); }) } } } </script> <style> #app { font-family: ‘Avenir‘, Helvetica, Arial, sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; text-align: center; color: #2c3e50; margin-top: 60px; } h1, h2 { font-weight: normal; } ul { list-style-type: none; padding: 0; } li { display: inline-block; margin: 0 10px; } a { color: #42b983; } </style>
方式2:在main.js中全局引入axios並添加到Vue原型中
### 3. 為自定義組件添加事件
Vue(十七)模塊化開發