【问题标题】:Understanding Vue components and routing了解 Vue 组件和路由
【发布时间】:2019-10-23 00:28:39
【问题描述】:

我正在学习how to build a website using a Vue frontend and Express REST backend

我创建了如下新路线:

/path/to/vue-client/routes/index.js

import Vue from 'vue';
import Router from 'vue-router';
import Hello from '@components/HelloWorld';
import Register from '@components/Register';

Vue.use(Router);

export default new Router({
    routes: [
        {
            path: '/',
            name: 'hello',
            component: Hello
        },
        {
            path: '/register',
            name: 'register',
            component: Register
        }        
    ]
});

/path/to/vue-client/src/components/Register.vue

<template>
  <div>
    <h1>{{ msg }}</h1>
    <p>
     This is the registration page.
    </p>
  </div>
</template>

<script>
export default {
  name: 'Register',
  props: {
    msg: String
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

现在,进行了这些更改后,我希望当我浏览到http://localhost:8080/register 时,我会看到显示注册页面,但是,浏览器只显示主页(无论我在浏览器 url 栏中输入什么!) .

我可以让注册页面显示的唯一方法是直接修改 App.vue:

/path/to/vue-client/src/App.vue

<template>
  <div id="app">
    <img alt="Vue logo" src="./assets/logo.png">
    <Register msg="Welcome to Your Vue.js App"/>
  </div>
</template>

<script>
import Register from './components/Register.vue'

export default {
  name: 'app',
  components: {
    Register
  }
}
</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;
}
</style>

如何获取另一个页面的链接(作为单个文件组件实现)以在 Vue 中工作?

【问题讨论】:

  • 在路由器的组件导入中尝试使用@/components 而不是@components

标签: vue.js


【解决方案1】:

在您的App.vue 中,您需要添加一个

<router-view></router-view>

在匹配特定路由时将呈现您的组件(在您的情况下为 Hello 或 Register)。

在组件内生成链接,然后在路由/组件之间导航

<router-link to="/">Go to Hello component</router-link>

cf VueJS 路由器文档:https://router.vuejs.org/guide/#html

【讨论】:

    猜你喜欢
    • 2019-06-29
    • 2018-03-13
    • 2018-10-01
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多