VUE3 routing
install
1. Direct download
https://unpkg.com/vue-router@4
NPM
Taobao image is recommended:
npm install -g cnpm --registry=https://registry.npm.taobao.org cnpm install vue-router@4
2. Simple case
<router-link> Is a component used to set up a navigation link and switch different HTML contents. to Property is the destination address, that is, the content to be displayed.
<script src="https://unpkg.com/vue@3"></script> <script src="https://unpkg.com/vue-router@4"></script> <div id="app"> <h1>Hello App!</h1> <p> <!--use router-link Components for navigation --> <!--Pass through `to` To specify the link --> <!--`<router-link>` A with the correct `href` Attribute `<a>` label--> <router-link to="/">Go to Home</router-link> <router-link to="/about">Go to About</router-link> </p> <!-- Route exit --> <!-- The components to which the route matches will be rendered here --> <router-view></router-view> </div>
router-link
Note that instead of using the regular a tag, a custom component router link is used to create the link. This allows Vue Router to change the URL and handle URL generation and encoding without reloading the page.
router-view
Router view will display the components corresponding to the url. You can put it anywhere to fit the layout.
// 1. Define routing components // You can also import from other files const Home = { template: '<div>Home</div>' } const About = { template: '<div>About</div>' } // 2. Define some routes // Each route needs to be mapped to a component. const routes = [ { path: '/', component: Home }, { path: '/about', component: About }, ] // 3. Create a routing instance and pass the 'routes' configuration // You can enter more configurations here, but keep it simple here for the time being const router = VueRouter.createRouter({ // 4. The implementation of history mode is provided internally. For simplicity, the hash pattern is used here. history: VueRouter.createWebHashHistory(), routes, // `Routes: abbreviation for routes' }) // 5. Create and mount the root instance const app = Vue.createApp({}) //Ensure_ use_ Routing instance enable //The whole application supports routing. app.use(router) app.mount('#app') // Now, the application has started!
< router link > related attributes
to
A link that represents the destination route. When clicked, the internal will immediately transfer the value of to to router.push(), so this value can be a string or an object describing the target location.
<!-- character string --> <router-link to="home">Home</router-link> <!-- Render results --> <a href="home">Home</a> <!-- use v-bind of JS expression --> <router-link v-bind:to="'home'">Home</router-link> <!-- Don't write v-bind You can also, just like binding other properties --> <router-link :to="'home'">Home</router-link> <!-- ditto --> <router-link :to="{ path: 'home' }">Home</router-link> <!-- Named route --> <router-link :to="{ name: 'user', params: { userId: 123 }}">User</router-link> <!-- With query parameters, the following result is /register?plan=private --> <router-link :to="{ path: 'register', query: { plan: 'private' }}">Register</router-link>
replace
If the replace attribute is set, when clicked, router.replace() will be called instead of router.push(). history records will not be left after navigation.
<router-link :to="{ path: '/abc'}" replace></router-link>
append
When the append property is set, its path is added before the current (relative) path. For example, we navigate from / A to a relative path B. If append is not configured, the path is / B. If append is configured, the path is / a/b
<router-link :to="{ path: 'relative/path'}" append></router-link>
tag
Sometimes I want to < router-link> Render to some kind of label, such as < li>. So use tag The prop class specifies which tag, and it will also listen for clicks and trigger navigation.
<router-link to="/foo" tag="li">foo</router-link> <!-- Render results --> <li>foo</li>
active-class
Sets the CSS class name used when the link is activated. It can be replaced by the following code.
<style> ._active{ background-color : red; } </style> <p> <router-link v-bind:to = "{ path: '/route1'}" active-class = "_active">Router Link 1</router-link> <router-link v-bind:to = "{ path: '/route2'}" tag = "span">Router Link 2</router-link> </p>
Pay attention here class use active-class="_active".
exact-active-class
Configure the class that should be activated when the link is accurately matched. It can be replaced by the following code.
<p> <router-link v-bind:to = "{ path: '/route1'}" exact-active-class = "_active">Router Link 1</router-link> <router-link v-bind:to = "{ path: '/route2'}" tag = "span">Router Link 2</router-link> </p>
event
Declare events that can be used to trigger navigation. It can be a string or an array containing strings.
<router-link v-bind:to = "{ path: '/route1'}" event = "mouseover">Router Link 1</router-link>
The above code sets event to mouseover, and the HTML content of navigation will change when the mouse moves to Router Link 1.
Vue3 Ajax(axios)
The Vue version recommends using axios to complete ajax requests.
Axios is a Promise based HTTP library that can be used in browsers and node.js.
Github open source address: GitHub - axios/axios: Promise based HTTP client for the browser and node.js
Installation method
Using cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
or
<script src="https://cdn.staticfile.org/axios/0.18.0/axios.min.js"></script>
Use npm:
$ npm install axios
Using bower:
$ bower install axios
Use yarn:
$ yarn add axios
usage method:
Vue.axios.get(api).then((response) => { console.log(response.data) }) this.axios.get(api).then((response) => { console.log(response.data) }) this.$http.get(api).then((response) => { console.log(response.data) })
GET method
You can simply read JSON data:
const app = { data() { return { info: 'Ajax test!!' } }, mounted () { axios .get('https://www.runoob.com/try/ajax/json_demo.json') .then(response => (this.info = response)) .catch(function (error) { // Request failure processing console.log(error); }); } } Vue.createApp(app).mount('#app')
use response.data Read JSON data:
<div id="app"> <h1>Site list</h1> <div v-for="site in info" > {{ site.name }} </div> </div> <script type = "text/javascript"> const app = { data() { return { info: 'Ajax test!!' } }, mounted () { axios .get('https://www.runoob.com/try/ajax/json_demo.json') .then(response => (this.info = response)) .catch(function (error) { // Request failure processing console.log(error); }); } } Vue.createApp(app).mount('#app') </script>
The format of parameters passed by GET method is as follows:
// Add parameter ID=12345 directly to the URL axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); // You can also set parameters through params: axios.get('/user', { params: { ID: 12345 } }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
POST method
The format of parameters passed by POST method is as follows:
axios.post('/user', { firstName: 'Fred', // Parameter firstName lastName: 'Flintstone' // Parameter lastName }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });
Execute multiple concurrent requests
function getUserAccount() { return axios.get('/user/12345'); } function getUserPermissions() { return axios.get('/user/12345/permissions'); } axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // Both requests are now complete }));
axios API
You can create a request by passing the configuration to axios.
axios(config) // Send POST request axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' } }); // GET request remote picture axios({ method:'get', url:'http://bit.ly/2mTM3nY', responseType:'stream' }) .then(function(response) { response.data.pipe(fs.createWriteStream('ada_lovelace.jpg')) }); axios(url[, config]) // Send GET request (default method) axios('/user/12345');