使用Vue Router时,根Vue实例的data、methods等属性应放置在哪里?
Where to place data, methods, and other Vue properties?
You don’t have to change where you put these core Vue options at all! They still live right in the Vue instance configuration object, alongside the router property. The $mount('#vueRoot') part is just an alternative to using the el option—they do the same thing (mounting the Vue instance to the DOM element), just at different times.
Here’s how your updated instance would look with all your familiar properties:
const vm = new Vue({ router, // Your router instance data() { return { msg: 'hello' } }, methods: { greet() { console.log(this.msg) } }, // ... other options like computed, watch, lifecycle hooks, etc. }).$mount('#vueRoot');
This works exactly like your old setup—you can still access this.msg or call this.greet() in the root instance’s template or hooks, just as before.
Do all contents need to be in components when using Vue Router?
Nope, that’s not a requirement! You can still include content directly in the root instance’s template (either via a template option in the instance, or inside the #vueRoot element in your HTML). However, the typical pattern with Vue Router is to use the root instance as a layout container that includes:
<router-link>elements for navigation<router-view>where the active route’s component will be rendered
For example, your root template might look like this in HTML:
<div id="vueRoot"> <!-- Navigation links in root --> <router-link to="/home">Home</router-link> <router-link to="/about">About</router-link> <!-- Route-specific content renders here --> <router-view></router-view> <!-- Static global content in root --> <footer>© 2024 My App</footer> </div>
That said, it’s best practice to keep route-specific content in individual components (since that’s what Vue Router is designed to handle), but you’re free to keep global, non-route-dependent content (like headers, footers, or global UI elements) in the root instance if it makes sense for your app.
To sum up: Your familiar Vue options stay right where you had them, and while components are central to Vue Router, you don’t have to move everything into components—only the parts tied to specific routes.
内容的提问来源于stack exchange,提问作者bbsimonbb

