Vue - - Nuxt.js for the whole family

Keywords: Programming axios Vue Javascript JSON

1. Directory structure

 

2. Aliases

  • On the vue page of nuxt.js, you can use ~or ~~ if you need to import resources from a directory such as assets or static.

 

3. Routing

Nuxt.js automatically generates the routing configuration for the vue-router module based on the pages directory structure.
To use routing between pages, we recommend using the <nuxt-link>tag.
<router-link>is the label of vue's original ecological switch path.
<nuxt-link>On the basis of original ecology, nuxt enhancement is carried out.(Official example: https://zh.nuxtjs.org/examples/named-views/)

  • Static Routing

  • Dynamic Routing

  • Dynamic Nested Routing

 

 

  • Dynamic Route Naming

Does the path'/news/123'match'_id.vue' or'_name.vue'?
We can use <nuxt-link>to solve these problems

<nuxt-link:to="{name:'news-id',params:{id:1002}}">News 2</nuxt-link>
<nuxt-link:to="{name:'news-name',params:{name:1003}}">News 3</nuxt-link>

Determine the component name by name: "xxx-yyy"
Pass value to corresponding parameter via params

  • Default Route

4. Custom Layout

Create components in the layouts directory: layouts/blog.vue
Use blog layout in the view you want

<script>
exportdefault{
layout:'blog'
//...
}
</script>

5. Error Page (write layouts/error.vue page to personalize error page)

<template>
<divclass="container">
<h1v-if="error.statusCode===404">Page does not exist</h1>
<h1v-else>Application Error Exception</h1>
<nuxt-linkto="/">home page</nuxt-link>
</div>
</template>
<script>
exportdefault{
props:['error'],
layout:'blog'//You can specify a custom layout for the error page
}
</script>
  • Nuxt.js page (Page components are actually Vue components, but Nuxt.js adds some special configuration items to these components)

<template>
<h1class="red">Hello{{name}}!</h1>
</template>
<script>
exportdefault{
//Processing data asynchronously, called before each load
asyncData(context){
//calledeverytimebeforeloadingthecomponent
return{name:'World'}
},
//State Tree (store) used to get data to populate the application before rendering the page
fetch(){
//Thefetchmethodisusedtofillthestorebeforerenderingthepage
},
//Configure Meta Tags for Current Page
head(){
//SetMetaTagsforthisPage
},
//andmorefunctionalitytodiscover
...
}
</script>
<style>
.red{
color:red;
}
</style>
<template>
<div>
//Detail page {{$route.params.id}} <br/>
<divclass="bg2"></div>
<divclass="bg3"></div>
</div>
</template>
<script>
exportdefault{
head:{
title:'Detail Page',
link:[
{rel:'stylesheet',href:'/style/img.css'}
],
script:[
{type:'text/javascript',src:'/js/news.js'}
]
}
}
</script>
<style>
.bg2{
background-image:url('~static/img/2.jpg');
width:300px;
height:300px;
background-size:300px;
}
</style>

6.nuxt Integration vuex

  • Write only the core content of vuex in nuxt

Write:

//state area, equivalent to defining variables
export const state = () => ({
  
})

//mutations area, used to modify data
export const mutations = {
  //Method name (state, value) {
    
  }
}
  • state area note implementation:
//state area, equivalent to defining variables
export const state = ()=> {
  return {

  }
}
//Omit Writing
export const state = () => ({

})
  • Case: 1) Create ~/store/index.js and write the following
//state area, equivalent to defining variables
export const state = () => ({
  pageInfo: ''
})

//mutations area, used to modify data
export const mutations = {
  setData( state , value) {
    state.pageInfo = value
  }
}

Use

<script>
import {mapState,mapMutation} from 'vuex'
export default {
    //state area, combined with properties that need to be calculated
    computed: {
        ...mapState([variable,Variable 2,....])
    },
    //mutations area, modifying data, needs to be combined with methods
    methods: {
        ...mapMutation([Method Name,Method Name 2,....])
    }, 
}
</script>

2) Complete fetch operation

<template>
  <div>
      {{ this.$store.state.pageInfo }}
  </div>
</template>

<script>
export default {
  async fetch( {$axios, store } ) {
    //Send ajax
    let { data } = await $axios.get('/userservice/user/list')
    console.info( data )
    //Save query results in vuex
    store.commit('setData', data.data )
  }
}
</script>

<style>

</style>

 

7. Integrating axios

  • When you build a project, nuxt.js automatically integrates with axios if you choose the axios component.
  • Integration effect:

1) package.json has axios version

2) nuxt.config.js adds axios as a module

  • Common configurations, modify nuxt.config.js to configure the baseURL

  • Send ajax using Axios (in the vue page, manipulate ajax by this.$axios.xxx().this.$axios is equivalent to the previous axios.)
this.$axios.post("/search-service/search",this.searchMap).then(res=>{
//Get Query Results
this.searchResult=res.data.data;
});
  • Send asynchronous data using asyncData (send an ajax to send an ajax request through content.$axios, equivalent to using Axios before).)
asyncasyncData(content){
let{data}=awaitcontent.$axios.get('/web-service/news',{
params:{
pageNum:1,
pageSize:8,
sortWay:'asc'
}
})
return{news:data.data}
},

  • Send multiple ajax
asyncasyncData(content){
let[Result 1,Result 2]=awaitPromise.all([ajax Request 1,ajax Request 2])
return{
topNews:Result 1 data,
categorys:Data for Result 2
}
},
asyncasyncData(content){
let[res,res2]=awaitPromise.all([
content.$axios.get("/web-service/news",{
params:{
pageNum:1,
pageSize:8,
sortWay:'asc'
}
}).then(res=>res),
content.$axios.get("/web-service/categorys")
.then(res=>res),
])
return{
topNews:res.data.data,
categorys:res2.data.data
}
},
  • Send ajax using fetch
<template>
<div>
//about
</div>
</template>
<script>
//import{test}from'~/plugins/api.js'
import{mapState,mapMutations}from'vuex'
exportdefault{
asyncfetch({store,$axios}){
let{data}=await$axios.get('/web-service/news',{
params:{
pageNum:1,
pageSize:8,
sortWay:'asc'
}
})
store.commit('setData',data.data)
},
asyncmounted(){
let{data}=awaitthis.$axios.get('/web-service/news',{
params:{
pageNum:1,
pageSize:8,
sortWay:'asc'
}
})
localStorage.setItem('newssss',data.data.data)
}
}
</script>
<style>
</style>

8. Plugins: Customize axios

  • Step 1: Configure the plug-in

  • Step 2: Write api.js to enhance the built-in $axios
//Custom Functions
constrequest={
test:(params)=>{
returnaxios.get('/web-service/test',{
params
})
},
}
varaxios=null
exportdefault({$axios},inject)=>{
//3) Save built-in axios
axios=$axios
//4) Submit custom functions to nuxt
//Usage 1: In vue, this.$request.xxx()
//Usage 2: In nuxt's asyncData, content.app.$request.xxx()
inject('request',request)
}

9.Vuex State Tree

  • Each.js file in the store directory is converted to a named submodule specified in the state tree.index is the root module

1). Root module data operations

  • Step 1: Modify store/index.js to add a counter variable and continue the cumulative operation

 

exportconststate=()=>({
counter:0
})
exportconstmutations={
increment(state){

state.counter++
}
}
  • Step 2: On the page, use
<template>
<div>
//Home page {{counter}}
<inputtype="button"value="+"@click="increment"/>
</div>
</template>
<script>
import{mapState,mapMutations}from'vuex'
exportdefault{
computed:{
...mapState(['counter'])
},
methods:{
...mapMutations(['increment'])
},
}
</script>
<style>
</style>

2). Data operations for other modules

  • Step 1: Create additional modules

exportconststate=()=>({
money:0
})
exportconstmutations={
addmoney(state){
state.money+=5
}
}
  • Step 2: Use the data in the specified module
<template>
<div>
//Home page {{money}}
<inputtype="button"value="+"@click="addmoney"/>
</div>
</template>
<script>
import{mapState,mapMutations}from'vuex'
exportdefault{
computed:{
money(){
returnthis.$store.state.book.money
}
},
methods:{
...mapMutations({
addmoney:'book/addmoney'
})
},
}
</script>
<style>
</style>

Posted by nemesis.2002 on Sun, 29 Mar 2020 19:53:29 -0700