vue-router跳转页面的方法

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

vue-router跳转页面的方法

阁主乄   2020-05-15 我要评论

使用 Vue.js 做项目的时候,一个页面是由多个组件构成的,所以在跳转页面的时候,并不适合用传统的 href,于是 vue-router 应运而生

官方文档请点击这里

## vue-router

第一步当然是安装了,用npm安装命令

npm install vue-router --save-dev

第二步在.vue组件里添加标签,格式如下

<div id="app">
<p>
  <!-- 使用 router-link 组件来导航. -->
  <!-- 通过传入 `to` 属性指定在main.js文件设置的别名链接,如/1 -->
  <!-- <router-link> 默认会被渲染成一个 `<a>` 标签 -->
  <router-link to="/1">Go to Foo</router-link>
</p>
<!-- 路由出口 -->
<!-- 点击<router-link>的时候指定的页面将渲染在这里 -->
<router-view></router-view>
</div>

第三步在main.js文件里配置路由,格式如下

import VueRouter from 'vue-router'

// 1. 定义(路由)组件。
// 加载组件
import Page01 from './max'

Vue.use(VueRouter)
//全局安装路由功能

// 2. 定义路由
// 每个路由应该映射一个组件。 
const routes = [
 { path: '/1', component: Page01 } 
 //前面to指定的地方 path /1
]

// 3. 创建 router 实例,然后传 `routes` 配置
const router = new VueRouter({
 routes
})

// 4. 创建和挂载根实例。
// 记得要通过 router 配置参数注入路由,
// 从而让整个应用都有路由功能
new Vue({
 el: '#app',
 template: '<App/>',
 components: { App },
 router
})

// 现在,就可以重启试试了!

注意 routes router 是不一样的单词,别眼花了

路由就是这么的简单!

props

父组件向子组件传值

在子组件里添加 prors ,格式如下

props: [
  'rimag',
  'hyaline',
  'levels',
  'ohyaline'
],

然后是在父组件里向子组件里传值,格式如下

//HTML

<nv-nav :rimag=mgse :hyaline=ortiy :levels=vels :ohyaline=orctiy></nv-nav>
// 传值用绑定

//JS

data () {
  return {
   mgse: -20.62,
   orctiy: 0,
   vels: -1,
   ortiy: 0
  }
}

点击后父组件就会将data里的数据绑定到子组件的props里

$emit

子组件改变父组件的值,通过$on将父组件的事件绑定到子组件,在子组件中通过$emit来触发$on绑定的父组件事件

先在父组件里将值绑定给子组件并监听子组件变化,格式如下

//HTML

<nv-nav v-on:child-say="listen"></nv-nav>

//JS

listen: function (mgs, orc, cel, ort) {
 this.mgse = mgs
 this.orctiy = orc
 this.vels = cel
 this.ortiy = ort
}

之后在子组件data里建要改变的值,格式如下

mgs: -20.62,
orc: 0,
cel: -1,
ort: 0

然后建个方法

dis: function () {
 this.$emit('child-say', this.mgs, this.orc, this.cel, this.ort)
}

给某个元属添加点击事件触发刚建的方法

<aside @click="dis"></aside>

有点乱,欢迎大家来纠正

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们