1.0 vue创建项目中各部分之间的相互依赖关系
注:文中所述的主组件渲染是在将index.html中的DOM拿过去后利用主组件添加的方式进行操作的,也即最初页面的框架还是由index.html提供的。
1.1 构建的项目中目录表:![在这里插入图片描述](https://img-blog.csdnimg.cn/20210625100059986.png#pic_center)
其中主要是:main.js、router文件夹;
其中main.js内容如截图,是项目渲染的入口,代码块为:
import Vue from 'vue'
import App from './App'
import router from './router'
Vue.config.productionTip = false
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
render: h => h(App)
})
其中主组件为App.vue,此处实现方式是单页面富应用,主页面渲染框架就是App.vue,代码如下:
<template>
<div id="app">
<img src="./assets/logo.png" />
<router-link to="/home" tag="button" replace="">首页</router-link>
<router-link to="/about" replace="">关于</router-link>
<router-link v-bind:to="'/user/' + userId">用户</router-link>
<!-- <router-link to="/profile">档案</router-link> -->
<router-link
:to="{
path: '/profile',
query: { name: 'zhang' }, // 此处向profile.vue要得到的值进行取值
}"
>档案</router-link
>
<!-- <button @click="homeClick">首页</button>
<button @click="aboutClick">关于</button> -->
<router-view></router-view>
</div>
</template>
<script>
export default {
name: "App",
data() {
return {
userId: "lisi",
};
},
methods: {
homeClick() {
// this.$router.push("home");
this.$router.replace("home");
},
aboutClick() {
this.$router.push("about");
},
},
};
</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;
}
.router-link-exact-active,
router-link-active {
color: red;
}
</style>
其中主组件中嵌套了子组件,子组件的添加方式就是利用路由表进行配置渲染,此处用到路由,路由配置在index.js文件中,代码如下:
// 配置路由信息
import Vue from 'vue'
import VueRouter from 'vue-router'
// import home from '../components/home'
// import about from '../components/about'
// import user from '../components/user'
const home = () => import('../components/home')
const about = () => import('../components/about')
const user = () => import('../components/user')
const homenews = () => import('../components/homenews')
const homemessage = () => import('../components/homemessage') // 此处到处文件夹的名字所以主要决定因素是文件的命名
const profile = () => import('../components/profile')
// 安装
Vue.use(VueRouter)
// Vuerouter
const routes = [
{
path: '',
//重定向默认显示首页
redirect: '/home'
},
{
path: '/home',
component: home,
children: [
{
path: '',
redirect: 'news'
},
{
path: 'news', // 此处路径主要用作页面导航栏中显示的路径,并且在组件中使用时to的指向一致
component: homenews //此处对应新定义的变量名代替组件出现
}, {
path: 'message',
component: homemessage
}]
}, {
path: '/about',
component: about
}, {
path: '/user/:userId',
component: user
},
{
path: '/profile',
component: profile
}
]
const router = new VueRouter({
routes,
mode: 'history',
linkActiveClass: 'active'
})
export default router