全局安装Vue CLI
npm install -g @vue/cli
快速创建基于vue-router的应用
得到如下目录,
改造项目
- main.js,不做修改
import { createApp } from 'vue'
import App from './App.vue'
import router from './router'
createApp(App).use(router).mount('#app')
- app.vue,添加针对Test页面的路由
<template>
<div id="nav">
<router-link to="/">Home</router-link> |
<router-link to="/about">About</router-link>
<router-link to="/test">Test</router-link>
</div>
<router-view/>
</template>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
}
#nav {
padding: 30px;
}
#nav a {
font-weight: bold;
color: #2c3e50;
}
#nav a.router-link-exact-active {
color: #42b983;
}
</style>
- 对Home、About和Test路由页面内容,稍作修改
<template>
<div class="home">
<h1>This is an home page</h1>
</div>
</template>
<script>
export default {
name: 'Home'
}
</script>
<template>
<div class="about">
<h1>This is an about page</h1>
</div>
</template>
<script>
export default {
name:"About"
}
</script>
<template>
<HelloWorld></HelloWorld>
</template>
<script>
import HelloWorld from "@/components/HelloWorld.vue";
export default {
components: { HelloWorld },
name:"Test",
component:{
HelloWorld
}
}
</script>
<template>
<div class="hello">
<h1>Test for hello world</h1>
</div>
</template>
<script>
export default {
name: 'HelloWorld',
}
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
margin: 40px 0 0;
}
ul {
list-style-type: none;
padding: 0;
}
li {
display: inline-block;
margin: 0 10px;
}
a {
color: #42b983;
}
</style>
启动应用,测试效果
npm run serve
,测试效果如下,