[vuejs/vue-router]直接在地址栏里输入路由,路由不能生效?

2023-12-15 954 views
8

我在尝试文档中的Basic Usage里面的例子的时候发现,只要进入了路由之后,再刷新页面或者复制链接到新的页面的地址栏里面,路由并不能起到作用?请问这是本来的特性?还是可以通过其他方法解决?

回答

3

这是我的index.html代码。

 <!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>test</title>
    <script type="text/javascript" src="js/bundle.js"></script>
</head>
<body>
    <div id="app">
        <h1>Hello App!</h1>
        <p>
            <!-- use v-link directive for navigation. -->
            <a v-link="/foo">Go to Foo</a>
            <a v-link="/bar">Go to Bar</a>
        </p>
        <!-- use router-view element as route outlet -->
        <router-view></router-view>
    </div>
</body>
</html>

这是我的app.js的代码

var Vue = require('../bower_components/vue/dist/vue.min.js');
var VueRouter = require('../bower_components/vue-router/dist/vue-router.min.js');
Vue.use(VueRouter);
// define some components
var Foo = Vue.extend({
    template: '<p>This is foo!</p>'
})

var Bar = Vue.extend({
    template: '<p>This is bar!</p>'
})

// the router needs a root component to render.
// for demo purposes, we will just use an empty one
// because we are using the HTML as the app template.
var App = Vue.extend({})

// create a router instance
// you can pass in additional options here, but
// let's keep it simple for now.
var router = new VueRouter()

// define some routes.
// each route should map to a component.
// we'll talk about nested routes later.
router.map({
    '/foo': {
        component: Foo
    },
    '/bar': {
        component: Bar
    }
})

// now we can start the app!
// router will create an instance of App and mount to
// the element matching the selector #app.
router.start(App, '#app')

我通过bower安装了vue和vue-router,然后使用webpack将app.js打包成了bundle.js。

$ webpack ./app.js bundle.js

当我在浏览器中直接打开index.html的时候,这个例子可以正常运行的。但是再次刷新之后或者是点击了按钮之后刷新,似乎就不起作用了。这是不起作用时的情况: notworks

0

在Mac版本下的chrome调试刷新是可以起作用的,但是在windows版本下却不行。

8

我这里无法重现啊... windows Chrome / IE 都正常... 你试试别用 bower,用 npm 安装,然后直接 require('vue')require('vue-router').

6

使用问题:引用的js文件放在head中和body中的差异。貌似首次从原始路径加载页面会触发渲染(就算js放在head中),否则刷新如果不是body中引用(放在head中)由于页面加载不会触发执行,导致没有渲染。

3

@niwho js 文件要放在 router.start() 的目标元素后面...

2

我也同样遇到这问题。我把代码写完,发现组件已经加载了,但死活不渲染页面。 我一点点删减代码,后来删减到跟官方demo一样,还是不渲染。原来是js加载引入顺序的问题,哎。 @niwho 你说的对