vue 通过按钮使用组件跳转页面_Vue组件显示与页面跳转

最近在学习vue框架,从网上找了一个实例但是只有一个页面,就是所有组件都放到App.vue里,结果点击按钮,所有内容都显示在当前页面,但是我想实现页面的跳转,搞了好几天,终于在网上找到了一个例子。下面贴出在一个页面添加组件以及跳转页面的代码。

单页应用(SPA),那么整个项目有以下三个文件是必要的:

一个html文件:index.html

一个webpack打包时的入口js文件:main.js

一个根vue组件,作为其他组件的挂载点:app.vue    (作为首页)

1、实现页面的跳转:

1、首先在conponent文件夹中创建index.vue和hello.vue文件

                   

2、修改main.js文件

3、修改App.vue

4、修改index.html

这样就会把渲染出来的页面挂载到这个id为app的div里了。

2、在页面中添加组件

如果我在App.vue里添加组件login.vue,然后配置路由main.js

运行结果如下:

但是如果我想把这个组件放到hello.vue组件里按照该方法就不对了,不知道为什么。

这个错误的意思貌似是找不到路径,

后来解决了这个问题,方法是对的,但是路径需要改一下。        import login from '../components/login.vue';(有两个点)

注:对于路径的写法:./ 当前目录 ../ 父级目录 / 根目录

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Vue.js 中,可以通过按钮点击来实现组件之间的页面或替换。有几种方式可以实现这一功能,以下是其中两种常见的方法: 1. 使用 Vue Router:Vue Router 是 Vue.js 官方提供的路由管理插件。首先,你需要安装和配置 Vue Router。然后,在你的按钮点击事件中,使用 `router.push()` 方法实现页面。例如: ```javascript <template> <div> <button @click="goToAnotherPage">到另一个页面</button> </div> </template> <script> import { mapActions } from 'vuex'; export default { methods: { ...mapActions(['goToAnotherPage']), }, }; </script> ``` ```javascript // 在路由配置文件中 import VueRouter from 'vue-router'; import AnotherPage from './components/AnotherPage.vue'; const routes = [ { path: '/another-page', component: AnotherPage }, // 其他路由配置... ]; const router = new VueRouter({ routes, }); export default router; ``` 2. 使用条件渲染:在主页面组件中,使用条件渲染来控制要显示组件。通过点击按钮,改变条件渲染的变量,从而切换到不同的组件。例如: ```javascript <template> <div> <button @click="toggleComponent">切换组件</button> <component v-if="showComponent" :is="currentComponent"></component> <component v-else :is="anotherComponent"></component> </div> </template> <script> import AnotherComponent from './components/AnotherComponent.vue'; export default { data() { return { showComponent: true, }; }, computed: { currentComponent() { return this.showComponent ? 'MainComponent' : 'AnotherComponent'; }, }, components: { AnotherComponent, }, methods: { toggleComponent() { this.showComponent = !this.showComponent; }, }, }; </script> ``` 以上是两种常见的实现方式,你可以根据具体的需求选择适合你的方法。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值