路由逻辑跳转、组件数据局部化处理
一、
1)根组件:App.vue <template> <div id="app"> <router-view /> </div> </template> 2)路由配置:router/index.js const routes = [ { path: '/', name: 'Home', component: Home } ]; 3)组件:views和components文件夹 i)删除除Home.vue以为的所有组件 ii)初始化Home.vue <template> <div class="home"> </div> </template> 4)分类管理资源:assets文件夹 建立img、css、js子文件夹,删除原来的资源 5)如果要修改页面标签图标 替换public文件夹下的favicon.ico图片文件
图片:
1、

3、

4、

5、

二、
1)不管页面组件还是小组件,都可能会被多次复用
2)复用组件的原因,其实就是复用组件的 页面结构、页面样式、页面逻辑
3)但是页面上的数据需要区分(被复用的两个组件数据多少是有区别的),所以组件的数据要做局部化处理
4)借助函数可以产生局部作用域的特点,为每一次复用组件产生一个独立的作用域
语法:
data () {
return {
// 数据们
}
}
子组件Beat.vue文件(建在components文件夹下)中:

<template> <div class="beat" @click="count += 1"> {{ count }}下 </div> </template> <script> export default { name: "Beat", // 不管是页面组件还是小组件,都可能被复用,页面结构与样式都可以采用一套,但是数据一定要相互独立 data () { return { count: 0 } } } </script> <style scoped> .beat { width: 100px; height: 100px; background-color: orange; text-align: center; line-height: 100px; border-radius: 50%; } </style>
父组件home.vue文件(views文件夹下)中

<template> <div class="home"> <Beat/> <Beat/> </div> </template> <script> import Beat from '@/components/Beat' export default { components: { Beat, } } </script>
三、
1)很多时候,我们需要通过普通按钮的逻辑,或是直接在某些逻辑中完成页面的跳转
2)可以通过在逻辑中用 this.$router.push() 来完成前往目标页,两种语法如下
this.$router.push('路径')
this.$router.push({name: '路由名'})
3)在做移动端项目时,没有像浏览器那样的前进后台键,页可以用 this.$router.go() 来完成前进后退,语法如下
前进后退:this.$router.go(正负整数),正式代表前进,负数代表后台,数值就是步长
案例:
home.vue文件中
<template> <div class="home"> <Nav/> <h1>主页</h1> <button @click="goPage('/first')">前往第一页</button> | <button @click="goPage('/second')">前往第二页</button> | <button @click="goBack(-1)">后退一页</button> | <button @click="goBack(-2)">后退二页</button> | <button @click="goBack(1)">前进一页</button> </div> </template> <script> import Nav from '@/components/Nav' export default { methods: { goPage(path) { // 可以通过 this.$router 完成逻辑跳转 this.$router.push(); }, goBack(num) { // 一般在移动端项目上运用 this.$router.go(num); } }, components: { Nav, } } </script>
Nav.vue文件在建在components文件夹下
。

浙公网安备 33010602011771号