单文件组件格式如下
//放置组件模板
export default {
name: ' '
}
Vue中的路由
路由就是根据网址的不同,返回不同的内容给用户。
实现不同网页显示不同的内容。
实现点击某些DOM元素跳转到某些页面。
因为点击某些元素运行了某函数并在函数中实现页面跳转 this.$router.push(" ")
入口文件main.js挂载了app这个挂载点,同时引入App组件和路由。
//main.js文件
import App from './App'
import router from './router' //vue自动引入了router文件夹下的index.js文件
new Vue({
el: '#app', //挂载点
// 键和值一样,写一个即可
router, // router:router
store, // store:store
components: { App },// components: { App :App},
template: ''
})
App.vue组件中使用写入了路由,使得每个页面显示的是根据路由设置当前地址所对应的内容。
//App.vue文件
export default {
name: 'App'
}
以下为router目录下的index.js文件,文件写明了访问某个路径时显示哪个组件以及组件名是什么。这些组件都需要在文件头的部分进行引入。
动态路由,根据选中内容的不同,点击跳转到不同的页面。
(注意动态路由的代码书写方式,组件中元素绑定路由时的写法也要注意,下文会说明。)
{
// 动态路由/address/
path:'/detail/:id',
name:'Detail',
component:Detail
}],
//router/index.js文件
import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/Pages/Home' //引入路由中显示的组件,@指向src目录
import City from '@/Pages/city/City'
import Detail from '@/Pages/detail/Detail'
Vue.use(Router)
export default new Router({
routes: [
{
path: '/', //访问根路径时显示的组件是什么,组件名是什么
name: 'Home',
component: Home
},{
path:'/city',
name:'City',
component:City
},{
// 动态路由/address/
path:'/detail/:id',
name:'Detail',
component:Detail
}],
// 页面切换时始终回到最顶部
scrollBehavior (to, from, savedPosition) {
return { x: 0, y: 0 }
}
})
在写每个组件的.vue文件的过程中,要在逻辑部分注明它的name,这与router/index.js中申明的组件name保持一致。
export default{
name:'City',
}
在需要实现点击跳转的元素区域使用 to表示跳转到哪个页面,""内的内容按路由文件index.js配置的内容来确定格式。
下图绑定的是动态路由,:to=的内容由两部分组成。用+连接。
注:把加到我们需要实现页面跳转的标签外时,会把标签内一些字体颜色改变。这是因为默认是个标签。我们可以直接用包裹标签,再重新设定字体的颜色,但是其实有更好的方法。如图:把标签直接改为,然后在内加入tag="li",这样就可以解决字体颜色变化的问题了。
tag="li"
class="item border-bottom"
v-for="item of recommendList"
:key="item.id"
:to="'/detail/'+item.id"
>
{{item.title}}
{{item.desc}}
查看详情
this.$router.push(" ")
除了使用上述两种方法,还可以使用router的实例方法实现页面跳转。“ ”中写法与router/index.js中定义的形式保持一致。
export default new Router({
routes: [
{
path: '/',
name: 'Home',
component: Home
},{
path:'/city',
name:'City',
component:City
},{
// 动态路由/address/
path:'/detail/:id',
name:'Detail',
component:Detail
}],
// 页面切换时始终回到最顶部
scrollBehavior (to, from, savedPosition) {
return { x: 0, y: 0 }
}
})
用在函数中方式如下:
methods:{
nowhandleCityClick(){
// 改变完城市后跳转回首页
this.$router.push("./")
},
}