一、模块化开发
1、vue-router模块化(关于vue-router模块的开发)
1、安装vue-router模块:cnpm install vue-router -S
2、 编辑main.js,引入vue-router模块(Vue.prototype.$http=axios; //向Vue原型上添加$http功能,叫什么名字自己定义)
import Vue from 'vue'
import VueRouter from 'vue-router'//引入模块
import App from './App.vue'
import routerConfig from './router.config.js'//将路由规则写在router.config.js文件中,然后导入改文件
import axios from 'axios'
//使用VueRouter
Vue.use(VueRouter);
//创建路由实例
const router=new VueRouter(routerConfig);
Vue.prototype.$http=axios;
new Vue({
el: '#app',
render: h => h(App),
router
})
3、编辑App.vue
<template> <div id="app"> {{msg}} <h3> <router-link to="/home">主页</router-link> <router-link to="/news">新闻</router-link> </h3> <div> <keep-alive> <router-view></router-view> </keep-alive> </div> <hr> <button @click="send">发送AJAX请求</button> <MyButton @click.native="send"></MyButton> </div> </template> <script> // import axios from 'axios' import MyButton from './components/MyButton.vue' export default { name: 'app', data () { return { msg: 'Welcome to itany' } }, mounted(){ console.log(this.$route); }, watch:{//监视路由变化 $route:function(newValue,oldValue){ console.log('路由发生变化,跳转到:'+newValue.path); } }, methods:{ send(){ this.$http.get('https://api.github.com/users/tangyang8942') .then(resp => { console.log(resp.data); }).catch(err => { console.log(err); }); } }, components:{ MyButton } } </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>
4、创建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模块化(关于axios模块的开发)
1、安装axios模块:cnpm install axios -S
2、axios的使用方式(在上面的代码中都有体现):
方式1:在每个组件中引入axios
方式2:在main.js中全局引入axios并添加到Vue原型中
3、为自定义组件添加事件
在绑定事件的时候要添加上native修饰符
eg: <MyButton @click.native="send"></MyButton>