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 })
<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>
import Home from './components/Home.vue' import News from './components/News.vue' export default { routes:[ { path:'/home', component:Home }, { path:'/news', component:News } ] }
<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>
建立組件 MyButton.vue
html
使用自定義組件vue