Vue Study Notes: Components, Vuex, and Routing with Legacy APIs
These notes collect scaffold configuration, component communication, Vuex, and routing examples.
Scaffold file structure
The scaffold separates installed packages, public files, source code, configuration, and package metadata. The original structure is:
├── node_modules
├── public
│ ├── favicon.ico # Browser tab icon
│ └── index.html # Main page
├── src
│ ├── assets # Static assets
│ │ └── logo.png
│ ├── component # Components
│ │ └── HelloWorld.vue
│ ├── App.vue # Root component
│ └── main.js # Entry point
├── .gitignore # Git ignore rules
├── babel.config.js # Babel configuration
├── package.json # Package configuration
├── README.md # Project description
└── package-lock.json # Dependency lockfile
Vue builds
The source distinguishes the full vue.js build from runtime-only builds such as vue.runtime.xxx.js. The full build includes both the core runtime and a template compiler; a runtime-only build omits that compiler.
In the legacy setup described here, a runtime-only build cannot compile the template option at runtime. A render function receives createElement and uses it to describe the output.
The vue.config.js configuration file
Run vue inspect > output.js to inspect the scaffold configuration. Customize the scaffold through vue.config.js. The original reference is the Vue CLI documentation.
The ref attribute
A ref registers a reference to an element or child component, serving a role similar to an ID. On an HTML element it refers to the real DOM node; on a component it refers to the component instance.
Register a reference with <h1 ref="xxx">...</h1> or <School ref="xxx"></School>, then access it through this.$refs.xxx.
The props option
Props let a component receive data from its parent. For example, <Demo name="xxx" :age="xxx"/> passes two values.
Three declaration forms are shown in the source:
- Names only:
props: ['name', 'age']. - Types:
props: { name: String, age: Number }. - A detailed object with a type, required status, or default value, as below.
Props are read-only. The notes recommend copying a value into local data when local changes are needed, instead of assigning to the prop. They also note that required and default are generally not used together for the same purpose.
props:{
name:{
type:String,
required:true,
},
age:{
type:Number,
default:19
}
}
Mixins
A mixin extracts options shared by multiple components. Define an object containing options such as data and methods, then apply it globally with Vue.mixin(xxx) or locally with mixins: [xxx]. The original local example quoted the placeholder; here xxx denotes the mixin object.
{
data(){....},
methods:{....}
....
}
Plugins
Plugins extend Vue. In this legacy API, a plugin can be an object with an install method. Its first argument is the Vue constructor; subsequent arguments are supplied by the plugin user.
The example outlines adding a global filter, a global directive, a mixin, instance methods, and instance properties. Install a plugin using Vue.use(plugin).
plugin.install = function (Vue, options) {
Vue.filter(....)
Vue.directive(....)
Vue.mixin(....)
Vue.prototype.$myMethod = function () {...}
Vue.prototype.$myProperty = xxxx
}
Scoped styles
Use <style scoped> to limit styles to a component and reduce unintended conflicts.
Lessons from a TodoList example
The source proposes this component workflow:
- Split the static interface by function, using component names that do not conflict with HTML elements.
- Decide where state belongs. Data used by one component can stay there; data used by several components belongs in their nearest shared parent, a pattern known as lifting state.
- Implement interaction, starting with event bindings.
Props support parent-to-child communication. A parent can also pass a function that the child calls to communicate back.
Do not bind v-model directly to a prop because that would modify the prop. The notes also discourage mutating nested fields of an object prop, even when that does not produce a warning.
Web Storage
The notes describe browser storage through window.sessionStorage and window.localStorage, with a typical capacity of roughly 5 MB that varies by browser.
storage.setItem('key', 'value')adds or replaces a value.storage.getItem('person')returns the value for a key.storage.removeItem('key')removes one entry.storage.clear()clears all entries in that storage area.
The source describes session storage as lasting until the browser window closes, while local storage persists until cleared. An unavailable key returns null, and JSON.parse(null) also returns null. These are the original notes rather than a complete account of browser storage behavior.
Component custom events
Custom events provide child-to-parent communication. If A is the parent and B the child, bind an event listener to B from A; keep the callback in A.
Bind declaratively with <Demo @atguigu="test"/> or <Demo v-on:atguigu="test"/>. The legacy imperative approach uses a component ref and $on, as illustrated below.
Use the once modifier or $once for a one-time listener. Emit with this.$emit('atguigu', data) and remove a listener with this.$off('atguigu').
The source also describes the legacy native modifier for native DOM listeners on a component. When using $on, declare the callback in methods or use an arrow function so that this has the intended value.
<Demo ref="demo"/>
......
mounted(){
this.$refs.xxx.$on('atguigu',this.test)
}
Global event bus
A global event bus lets unrelated components communicate. The source installs the root instance as Vue.prototype.$bus inside beforeCreate.
The receiving component registers a listener on $bus, retaining its callback locally. Send data with this.$bus.$emit('xxxx', data). In beforeDestroy, remove the listeners used by that component with $off. The snippets below show installation and reception.
new Vue({
......
beforeCreate() {
Vue.prototype.$bus = this
},
......
})
methods(){
demo(data){......}
}
......
mounted() {
this.$bus.$on('xxxx',this.demo)
}
Publish and subscribe with pubsub-js
Another option for communication between arbitrary components is publish/subscribe.
- Install with
npm i pubsub-js. - Import with
import pubsub from 'pubsub-js'. - Subscribe in the receiving component and retain the returned subscription token.
- Publish with
pubsub.publish('xxx', data). - Unsubscribe in
beforeDestroyusingpubsub.unsubscribe(pid).
The receiver owns the callback. The code fragment below preserves the original subscription example.
methods(){
demo(data){......}
}
......
mounted() {
this.pid = pubsub.subscribe('xxx',this.demo)
}
nextTick
Call this.$nextTick(callback) to run a callback after the next DOM update has completed. Use it when changing reactive data and then performing an operation that depends on the updated DOM.
Transitions and animations
The transition wrapper adds CSS classes at appropriate points when elements are inserted or removed.
The legacy entering classes are v-enter for the start, v-enter-active during entry, and v-enter-to for the end. The leaving counterparts are v-leave, v-leave-active, and v-leave-to.
Wrap an element in <transition> and optionally give the transition a name. For multiple elements, use <transition-group> and give every item a key.
<transition name="hello">
<h1 v-show="isShow">你好啊!</h1>
</transition>
Development proxies in Vue CLI
The source gives two proxy configurations in vue.config.js. These are historical configuration examples.
Method 1: A single proxy
A simple devServer.proxy points to one backend. Requests can be sent to the frontend development origin, such as port 8080.
The source describes this configuration as easy to set up but limited: it cannot define several targets or fine-grained forwarding rules. Requests for resources not handled by the frontend are forwarded to the configured server. The snippet is an excerpt, not a complete configuration file.
devServer: {
proxy: "http://localhost:5000";
}
Method 2: Explicit rules
A rule object can map /api1 to port 5000 and /api2 to port 5001, remove prefixes with pathRewrite, and set changeOrigin.
The source explains that changeOrigin: true changes the forwarded Host header to the backend host, while false retains the frontend host. Its note describes the default as true in the source environment.
This approach supports multiple targets and selective forwarding at the cost of additional configuration and request prefixes.
module.exports = {
devServer: {
proxy: {
"/api1": {
target: "http:
changeOrigin: true,
pathRewrite: { "^/api1": "" },
},
"/api2": {
target: "http:
changeOrigin: true,
pathRewrite: { "^/api2": "" },
},
},
},
};
Slots
Slots let a parent insert HTML into a designated position in a child, providing another form of parent-to-child communication. The source covers default, named, and scoped slots.
For a default slot, the child uses <slot> with fallback content and the parent supplies content inside the component. Named slots place content in a selected child location.
With scoped slots, the child owns the data while the parent decides how to render it. In the final example, Category owns a games array; the parent renders the supplied values as either list items or headings. The examples retain legacy scope, slot-scope, and slot syntax.
Parent component:
<Category>
<div>html结构1</div>
</Category>
Child component:
<template>
<div>
<!-- Example markup -->
<slot>插槽默认内容...</slot>
</div>
</template>
Parent component:
<Category>
<template slot="center">
<div>html结构1</div>
</template>
<template v-slot:footer>
<div>html结构2</div>
</template>
</Category>
Child component:
<template>
<div>
<!-- Example markup -->
<slot name="center">插槽默认内容...</slot>
<slot name="footer">插槽默认内容...</slot>
</div>
</template>
Parent component:
<Category>
<template scope="scopeData">
<!-- Example markup -->
<ul>
<li v-for="g in scopeData.games" :key="g">{{g}}</li>
</ul>
</template>
</Category>
<Category>
<template slot-scope="scopeData">
<!-- Example markup -->
<h4 v-for="g in scopeData.games" :key="g">{{g}}</h4>
</template>
</Category>
Child component:
<template>
<div>
<slot :games="games"></slot>
</div>
</template>
<script>
export default {
name: "Category",
props: ["title"],
data() {
return {
games: ["红色警戒", "穿越火线", "劲舞团", "超级玛丽"],
};
},
};
</script>
Vuex
The following sections collect the original Vuex state-management notes.
1. Concept
Vuex is described as a Vue plugin for centralized state management. It provides shared read/write access for multiple components and supports communication across the application.
2. When to use it
Consider centralized state when multiple components need to share the same data.
3. Set up the store
Create src/store/index.js, import Vue and Vuex, call Vue.use(Vuex), define actions, mutations, and state, and export a Vuex.Store.
Import the store into main.js and pass it as the store option when creating the root instance. The two snippets show the store and the application entry point.
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const actions = {};
const mutations = {};
const state = {};
export default new Vuex.Store({
actions,
mutations,
state,
});
......
import store from './store'
......
new Vue({
el:'#app',
render: h => h(App),
store
})
4. Basic usage
Initialize the state and define the actions and mutations in the store. The example uses an action named jia to commit a mutation named JIA, which increments state.sum.
Read a value with $store.state.sum. Trigger an action with $store.dispatch('actionName', data) or commit a mutation with $store.commit('mutationName', data).
If no network request or additional business logic is required, the source notes that a component can commit directly without an intermediate action.
import Vue from "vue";
import Vuex from "vuex";
Vue.use(Vuex);
const actions = {
jia(context, value) {
context.commit("JIA", value);
},
};
const mutations = {
JIA(state, value) {
state.sum += value;
},
};
const state = {
sum: 0,
};
export default new Vuex.Store({
actions,
mutations,
state,
});
5. Getters
Use getters when a value needs to be derived from state. Define a getters option in the store and access a result with $store.getters.bigSum. The example multiplies state.sum by ten.
......
const getters = {
bigSum(state){
return state.sum * 10
}
}
export default new Vuex.Store({
......
getters
})
6. Four mapping helpers
The source shows object and array forms of four helpers:
mapStatemaps state values to computed properties.mapGettersmaps getters to computed properties.mapActionscreates methods that call$store.dispatch.mapMutationscreates methods that call$store.commit.
Import the helpers before using them. When mapped action or mutation methods need arguments, pass them explicitly in the template; otherwise an event binding may supply the event object instead.
computed: {
...mapState({sum:'sum',school:'school',subject:'subject'}),
...mapState(['sum','school','subject']),
},
computed: {
...mapGetters({bigSum:'bigSum'}),
...mapGetters(['bigSum'])
},
methods:{
...mapActions({incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
...mapActions(['jiaOdd','jiaWait'])
}
methods:{
...mapMutations({increment:'JIA',decrement:'JIAN'}),
...mapMutations(['JIA','JIAN']),
}
7. Modules and namespaces
Modules group related state and behavior, making a larger store easier to maintain. Set namespaced: true on a module and register it in the store's modules option.
The examples then show, in order:
- Direct state access through
this.$store.state.personAbout.listand namespacedmapState. - Direct getter access through
this.$store.getters['personAbout/firstPersonName']and namespacedmapGetters. - Namespaced
dispatchandmapActions. - Namespaced
commitandmapMutations.
The module definitions are illustrative fragments; placeholder values must be supplied before running them.
const countAbout = {
namespaced:true,
state:{x:1},
mutations: { ... },
actions: { ... },
getters: {
bigSum(state){
return state.sum * 10
}
}
}
const personAbout = {
namespaced:true,
state:{ ... },
mutations: { ... },
actions: { ... }
}
const store = new Vuex.Store({
modules: {
countAbout,
personAbout
}
})
this.$store.state.personAbout.list
...mapState('countAbout',['sum','school','subject']),
this.$store.getters['personAbout/firstPersonName']
...mapGetters('countAbout',['bigSum'])
this.$store.dispatch('personAbout/addPersonWang',person)
...mapActions('countAbout',{incrementOdd:'jiaOdd',incrementWait:'jiaWait'})
this.$store.commit('personAbout/ADD_PERSON',person)
...mapMutations('countAbout',{increment:'JIA',decrement:'JIAN'}),
Routing
A route maps a key to a value. In frontend routing, the key is a URL path and the value is a component; a router manages the collection of mappings.
1. Basic usage
The source installs vue-router with npm i vue-router, registers the legacy plugin using Vue.use(VueRouter), and creates a router with new VueRouter({ routes }).
Use <router-link> for navigation and configure its active-class if needed. Render the matched component at <router-view>. The examples below use the original Vue Router constructor API.
import VueRouter from "vue-router";
import About from "../components/About";
import Home from "../components/Home";
const router = new VueRouter({
routes: [
{
path: "/about",
component: About,
},
{
path: "/home",
component: Home,
},
],
});
export default router;
<router-link active-class="active" to="/about">About</router-link>
<router-view></router-view>
2. Notes
Route components are usually stored in pages, while reusable components go in components. In the setup described, switching away normally destroys the route component and returning mounts it again.
Each component has $route for current route information. The application router is available through $router.
3. Nested routes
Use children to define nested routes. A child path such as news should not start with / when it is intended to be relative to the parent. Link to the complete path, such as /home/news.
routes: [
{
path: "/about",
component: About,
},
{
path: "/home",
component: Home,
children: [
{
path: "news",
component: News,
},
{
path: "message",
component: Message,
},
],
},
];
<router-link to="/home/news">News</router-link>
4. Query parameters
Pass query values in a URL string or with a navigation object containing path and query. Read them from $route.query.id and $route.query.title. The source's string-form example is retained as a fragment.
<!-- Example markup -->
<router-link :to="/home/message/detail?id=666&title=你好">跳转</router-link>
<!-- Example markup -->
<router-link
:to="{
path: '/home/message/detail',
query: {
id: 666,
title: '你好',
},
}"
>跳转</router-link>
$route.query.id;
$route.query.title;
5. Named routes
Give a route a name to avoid repeating the full path when navigating. A link can then use { name: 'hello' }, optionally including a query object. The first snippet sketches a nested route; the second compares navigation forms.
{
path:'/demo',
component:Demo,
children:[
{
path:'test',
component:Test,
children:[
{
name:'hello'
path:'welcome',
component:Hello,
}
]
}
]
}
<!-- Example markup -->
<router-link to="/demo/test/welcome">跳转</router-link>
<!-- Example markup -->
<router-link :to="{ name: 'hello' }">跳转</router-link>
<!-- Example markup -->
<router-link
:to="{
name: 'hello',
query: {
id: 666,
title: '你好',
},
}"
>跳转</router-link>
6. Route params
Declare path parameters with placeholders such as detail/:id/:title. Supply them in a complete URL string or a navigation object containing the route name and a params object.
When using the object form with params, use name, not path, in the API described here. Read values with $route.params.id and $route.params.title.
{
path:'/home',
component:Home,
children:[
{
path:'news',
component:News
},
{
component:Message,
children:[
{
name:'xiangqing',
path:'detail/:id/:title',
component:Detail
}
]
}
]
}
<!-- Example markup -->
<router-link :to="/home/message/detail/666/你好">跳转</router-link>
<!-- Example markup -->
<router-link
:to="{
name: 'xiangqing',
params: {
id: 666,
title: '你好',
},
}"
>跳转</router-link>
$route.params.id;
$route.params.title;
7. Route props
Route props make parameters easier for a route component to receive. An object passes fixed values, true passes route params, and a function can construct a props object from the route, including query values. The snippet shows all three forms.
{
name:'xiangqing',
path:'detail/:id',
component:Detail,
// props:{a:900}
// props:true
props(route){
return {
id:route.query.id,
title:route.query.title
}
}
}
8. The replace attribute
The browser history can be updated with push, which adds an entry, or replace, which replaces the current one. Navigation normally uses push. Enable replacement with <router-link replace ...>News</router-link>.
9. Programmatic navigation
Use $router methods to navigate without a <router-link>. The example shows push, replace, forward, back, and go. Supply the intended values and history offset where needed.
this.$router.push({
name: "xiangqing",
params: {
id: xxx,
title: xxx,
},
});
this.$router.replace({
name: "xiangqing",
params: {
id: xxx,
title: xxx,
},
});
this.$router.forward();
this.$router.back();
this.$router.go();
10. Cache route components
Wrap <router-view> in <keep-alive> to keep selected components mounted when they are not displayed. The example uses include="News".
<keep-alive include="News">
<router-view></router-view>
</keep-alive>
11. Activation lifecycle hooks
The source introduces activated and deactivated for observing when a cached route component becomes active or inactive.
12. Navigation guards
Navigation guards can control route access. The source distinguishes global guards, per-route guards, and component guards.
A global beforeEach runs on initialization and before navigation. In the example it checks to.meta.isAuth and a local-storage value, then calls next() to proceed or displays a message. The example is a routing demonstration, not server-side authorization.
A global afterEach updates the document title from route metadata, falling back to vue_test. A per-route beforeEnter applies a similar check to a specific route. Component options beforeRouteEnter and beforeRouteLeave observe entry and departure. The three snippets show these categories.
router.beforeEach((to, from, next) => {
console.log("beforeEach", to, from);
if (to.meta.isAuth) {
if (localStorage.getItem("school") === "atguigu") {
next();
} else {
alert("暂无权限查看");
// next({name:'guanyu'})
}
} else {
next();
}
});
router.afterEach((to, from) => {
console.log("afterEach", to, from);
if (to.meta.title) {
document.title = to.meta.title;
} else {
document.title = "vue_test";
}
});
beforeEnter(to,from,next){
console.log('beforeEnter',to,from)
if(to.meta.isAuth){
if(localStorage.getItem('school') === 'atguigu'){
next()
}else{
alert('暂无权限查看')
// next({name:'guanyu'})
}
}else{
next()
}
}
beforeRouteEnter (to, from, next) {
},
beforeRouteLeave (to, from, next) {
}
13. Hash and history modes
The hash is the # and everything after it in a URL; that fragment is not included in an HTTP request to the server.
The source describes hash mode as keeping # in the address, with broad compatibility but potential friction in third-party apps that validate shared URLs strictly.
It describes history mode as offering cleaner addresses. Its compatibility comparison reflects the original notes. Deployment needs server support so that refreshing a nested route returns the application instead of a 404.
A note from today, for a future self.
